/** * Java Collections Framework > ArrayListExample.java * * Use an ArrayList to store objects. An ArrayList grows dynamically as * you add objects to it; it also shrinks dynamically when you remove objects * from it. * @author Feihong Hsu */ import java.util.ArrayList; // A growable array public class ArrayListExample { // This method prints the elements of the given ArrayList. public static void printArrayList(ArrayList list) { System.out.print( "ArrayList: " ); // If the list is not empty, print a comma-delimited list of all the // elements. Otherwise just print "empty". if (!list.isEmpty()) { for (int i=0; i < list.size(); i++) System.out.print( list.get(i) + ", " ); System.out.println(); } else System.out.println( "empty" ); } public static void main(String[] args) { ArrayList list = new ArrayList(); // Add five objects to the ArrayList. list.add("Popcorn"); list.add(new Double(63.0)); list.add(new StringBuffer("Butter")); list.add(new Integer(923)); list.add(new java.awt.Point(3, 6)); // "ArrayList: Popcorn, 63.0, Butter, 923, java.awt.Point[x=3,y=6]" printArrayList(list); // Remove the second element from the ArrayList. list.remove(1); // "ArrayList: Popcorn, Butter, 923, java.awt.Point[x=3,y=6]" printArrayList(list); // Remove the element that is an Integer with a value of 923. list.remove(new Integer(923)); // "ArrayList: Popcorn, Butter, java.awt.Point[x=3,y=6]" printArrayList(list); // Add an object to the first position of the ArrayList. list.add(0, new Long(788L)); // "ArrayList: 788, Popcorn, Butter, java.awt.Point[x=3,y=6]" printArrayList(list); // Ask if the list has a String with value "Popcorn". System.out.print( "ArrayList contains Popcorn? " ); System.out.println( list.contains("Popcorn") ); // Prints true // Remove all the elements from the ArrayList. list.clear(); // "ArrayList: empty" printArrayList(list); } } /* ArrayList: Popcorn, 63.0, Butter, 923, java.awt.Point[x=3,y=6], ArrayList: Popcorn, Butter, 923, java.awt.Point[x=3,y=6], ArrayList: Popcorn, Butter, java.awt.Point[x=3,y=6], ArrayList: 788, Popcorn, Butter, java.awt.Point[x=3,y=6], ArrayList contains Popcorn? true ArrayList: empty */