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.Objects.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.202.240