//from Deitel Java: How to Program // Fig. 21.1: VectorTest.java //CMIS 241: changed from Vector to ArrayList import java.util.*; public class ArrayListTestDeitel { private static final String colors[] = { "red", "white", "blue" }; public ArrayListTestDeitel() { ArrayList myArrayList = new ArrayList(); printArrayList( myArrayList ); // print myArrayList // add elements to the myArrayList myArrayList.add( "magenta" ); for ( int count = 0; count < colors.length; count++ ) myArrayList.add( colors[ count ] ); myArrayList.add( "cyan" ); printArrayList( myArrayList ); // print myArrayList // does myArrayList contain "red"? if ( myArrayList.contains( "red" ) ) System.out.println( "\n\"red\" found at index " + myArrayList.indexOf( "red" ) + "\n" ); else System.out.println( "\n\"red\" not found\n" ); myArrayList.remove( "red" ); // remove the string "red" System.out.println( "\"red\" has been removed" ); printArrayList( myArrayList ); // print myArrayList // does myArrayList contain "red" after remove operation? if ( myArrayList.contains( "red" ) ) System.out.println( "\"red\" found at index " + myArrayList.indexOf( "red" ) ); else System.out.println( "\"red\" not found" ); // print the size of myArrayList System.out.println( "\nSize: " + myArrayList.size() ); } // end constructor private void printArrayList( ArrayList myArrayListToOutput ) { if ( myArrayListToOutput.isEmpty() ) System.out.print( "myArrayList is empty" ); // myArrayListToOutput is empty else { // iterate through the elements System.out.print( "myArrayList contains: " ); Iterator items = myArrayListToOutput.iterator(); while ( items.hasNext() ) System.out.print( items.next() + " " ); } System.out.println( "\n" ); } public static void main( String args[] ) { new ArrayListTestDeitel(); // create object and call its constructor } } // end class ArrayListTestDeitel