Categories
Java

Converting an ArrayList to a single-typed Array

Supposedly you want to create an object that dynamically takes object parameters and stores them in an ArrayList. All of the objects are of the same type and instead of creating a new array every time you use an ArrayList because you can keep on adding objects to it and it will still retain the order.
Now, suppose want to get an new array of the type of objects that you put in the ArrayList back. You can use ArrayList‘s toArray() method, and get an array of Object objects. Or you can use the following call:

MyObject [] objectArray = (MyObject[])theArrayList.toArray(new MyObject[0]);

Grizzly but true.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Share