Source of UsingToArray.java


  1: // Fig. 19.5: UsingToArray.java
  2: // Using method toArray.
  3: import java.util.LinkedList;
  4: import java.util.Arrays;
  5: 
  6: public class UsingToArray 
  7: {
  8:    // constructor creates LinkedList, adds elements and converts to array
  9:    public UsingToArray()
 10:    {
 11:       String colors[] = { "black", "blue", "yellow" };
 12: 
 13:       LinkedList< String > links = 
 14:          new LinkedList< String >( Arrays.asList( colors ) );
 15: 
 16:       links.addLast( "red" );   // add as last item
 17:       links.add( "pink" );      // add to the end
 18:       links.add( 3, "green" );  // add at 3rd index
 19:       links.addFirst( "cyan" ); // add as first item      
 20: 
 21:       // get LinkedList elements as an array     
 22:       colors = links.toArray( new String[ links.size() ] );
 23: 
 24:       System.out.println( "colors: " );
 25: 
 26:       for ( String color : colors )
 27:          System.out.println( color );
 28:    } // end UsingToArray constructor
 29: 
 30:    public static void main( String args[] )
 31:    {
 32:       new UsingToArray();
 33:    } // end main 
 34: } // end class UsingToArray
 35: 
 36: 
 37: /**************************************************************************
 38:  * (C) Copyright 1992-2005 by Deitel & Associates, Inc. and               *
 39:  * Pearson Education, Inc. All Rights Reserved.                           *
 40:  *                                                                        *
 41:  * DISCLAIMER: The authors and publisher of this book have used their     *
 42:  * best efforts in preparing the book. These efforts include the          *
 43:  * development, research, and testing of the theories and programs        *
 44:  * to determine their effectiveness. The authors and publisher make       *
 45:  * no warranty of any kind, expressed or implied, with regard to these    *
 46:  * programs or to the documentation contained in these books. The authors *
 47:  * and publisher shall not be liable in any event for incidental or       *
 48:  * consequential damages in connection with, or arising out of, the       *
 49:  * furnishing, performance, or use of these programs.                     *
 50:  *************************************************************************/