// ArrayListDemoWithIterator.java (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // This program works like ArrayListDemo.java. // An iterator is used to access the array elements in method // print_array(). // 2005-06-06 File created. // 2005-06-06 Last modification. import java.util.* ; class ArrayListDemoWithIterator { static void print_array( ArrayList given_array ) { System.out.print( "\n\n " ) ; Iterator element_to_print = given_array.iterator() ; while ( element_to_print.hasNext() == true ) { System.out.printf( "%5s", element_to_print.next() ) ; } /**** // The following "foreach" loop can replace the above loop and // the iterator. for ( Object element_in_array : given_array ) { System.out.printf( "%5s", element_in_array ) ; } *****/ } /** // The following is an alternative version of the // print_array() method. Here it is a generic method. static void print_array( ArrayList given_array ) { System.out.print( "\n\n " ) ; for ( T element_in_array : given_array ) { System.out.printf( "%5s", element_in_array ) ; } } ***/ public static void main( String[] not_in_use ) { ArrayList array_of_integers = new ArrayList() ; array_of_integers.add( 202 ) ; array_of_integers.add( 101 ) ; array_of_integers.add( 505 ) ; array_of_integers.add( 404 ) ; System.out.print( "\n Value 404 has index: " + array_of_integers.indexOf( 404 ) ) ; print_array( array_of_integers ) ; array_of_integers.add( 2, 999 ) ; array_of_integers.add( 2, 888 ) ; print_array( array_of_integers ) ; array_of_integers.remove( 4 ) ; print_array( array_of_integers ) ; array_of_integers.remove( new Integer( 888 ) ) ; print_array( array_of_integers ) ; ArrayList another_array = new ArrayList() ; another_array.add( 777 ) ; another_array.add( 666 ) ; print_array( another_array ) ; array_of_integers.addAll( another_array ) ; print_array( array_of_integers ) ; array_of_integers.set( 3, array_of_integers.get( 3 ) + 7 ) ; print_array( array_of_integers ) ; } }