ArrayLists and toArray

     

Say that you have an ArrayList (a java.util.ArrayList is a type of List that works like an array, but is automatically resizable). ArrayLists hold java.lang.Object s.

 

 ArrayList myObjArrayList = new ArrayList(); //put stuff into myObjArrayList without generics, //you can retrieve them only as type Object //initialize a new array that has as many elements //as the ArrayList has: MyObject myObjArray[] = new MyObject[myObjArrayList.size()]; //instantly put all of the elements from //the ArrayList into the array, //and they are of the proper type: myObjArray = myObjArrayList.toArray(myObjArray); 

You now have a regular array that holds objects of type MyObject. You get this without having to loop over each item in the ArrayList and call its get method and perform a cast.

Neat.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net