// ArrayListMethods.java (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // This program demonstrates the methods of the standard // class ArrayList. // The removeRange() method of class ArrayList is a protected // method, and thus not usable in this program. // 2004-09-26 File created. // 2005-06-07 Last modification. import java.util.* ; class ArrayListMethods { static void print_array( ArrayList given_array ) { System.out.print( "\n\n " ) ; for ( int element_index = 0 ; element_index < given_array.size() ; element_index ++ ) { System.out.printf( "%5s", given_array.get( element_index ) ) ; } } 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 array_of_characters = new ArrayList() ; array_of_characters.addAll( Collections.nCopies( 5, 'Z' ) ) ; print_array( array_of_characters ) ; array_of_integers.addAll( array_of_characters ) ; print_array( array_of_integers ) ; array_of_integers.remove( 3 ) ; array_of_integers.remove( 3 ) ; print_array( array_of_integers ) ; array_of_integers.clear() ; array_of_integers.add( 99.99 ) ; print_array( array_of_integers ) ; array_of_integers.clear() ; array_of_integers.add( 333 ) ; array_of_integers.add( 334 ) ; array_of_integers.add( 335 ) ; array_of_integers.add( 336 ) ; print_array( array_of_integers ) ; Object[] array_of_objects = array_of_integers.toArray() ; Collections.addAll( array_of_integers, array_of_objects ) ; print_array( array_of_integers ) ; Integer[] new_array_of_integers = new Integer[ 3 ] ; new_array_of_integers = array_of_integers.toArray( new_array_of_integers ) ; Collections.addAll( array_of_integers, new_array_of_integers ) ; print_array( array_of_integers ) ; } } /*** The second array could alternatively be created with the statement ArrayList array_of_characters = new ArrayList( Collections.nCopies( 5, 'Z' ) ) ; ***/