// CollectionsMethods.java (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // This program demonstrates the methods of the standard // class Collections. An ArrayList array is used as a // sample collection. // 2005-05-28 File created. // 2005-05-28 Last modification. import java.util.* ; class CollectionsMethods { 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 ).toString() ) ; } } public static void main( String[] not_in_use ) { ArrayList array_of_integers = new ArrayList() ; array_of_integers.add( 333 ) ; array_of_integers.add( 444 ) ; array_of_integers.add( 555 ) ; array_of_integers.add( 666 ) ; array_of_integers.add( 777 ) ; array_of_integers.add( 888 ) ; array_of_integers.add( 999 ) ; print_array( array_of_integers ) ; System.out.print( " original array" ) ; Collections.swap( array_of_integers, 0, 6 ) ; print_array( array_of_integers ) ; System.out.print( " after swapping" ) ; Collections.sort( array_of_integers ) ; print_array( array_of_integers ) ; System.out.print( " after sorting" ) ; Collections.reverse( array_of_integers ) ; print_array( array_of_integers ) ; System.out.print( " after reversing" ) ; Collections.shuffle( array_of_integers ) ; print_array( array_of_integers ) ; System.out.print( " after shuffling" ) ; Collections.rotate( array_of_integers, 2 ) ; print_array( array_of_integers ) ; System.out.print( " after rotating by 2 positions" ) ; System.out.print( "\n\n max element: " + Collections.max( array_of_integers ) ) ; System.out.print( "\n\n min element: " + Collections.min( array_of_integers ) ) ; Collections.fill( array_of_integers, 111 ) ; print_array( array_of_integers ) ; System.out.print( " after filling" ) ; // It is not possible to call addAll() and supply an int[] array // The following statement thus makes an Integer[] array. // Note that addAll() takes a varying number of parameters. Integer[] more_traditional_array = { 606, 505 } ; Collections.addAll( array_of_integers, 101, 102 ) ; Collections.addAll( array_of_integers, more_traditional_array ) ; print_array( array_of_integers ) ; System.out.print( " after addAll()" ) ; } }