O'Reilly logo

Java Garage by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required