How to Convert ArrayList to Array in Java

In this post we’ll see how to convert ArrayList to array in Java. Since internal implementation of ArrayList uses an array internally to store its element so ArrayList class itself provides methods to convert ArrayList to array. There are two overloaded toArray() methods.

  • toArray()– Returns an array containing all of the elements in this list in proper sequence. The returned array will be “safe” in that no references to it are maintained by this list. Returned array is of type Object.
  • toArray(T[] a)– Returns an array containing all of the elements in this list in proper sequence. The runtime type of the returned array is that of the specified array.

Though one problem with using these methods to convert ArrayList to array in Java is that the reference of the stored objects are shared between both ArrayList and converted array. Any modification to any stored object will be reflected in other data structure too. Let’s see the conversion and then reflected modification through an example. For that we’ll have to store custom objects in ArrayList so here is a class whose objects are stored in ArrayList.

Using toArray(T[] a) method to convert ArrayList to array

Here we have an ArrayList storing objects of type Employee. Then this ArrayList is converted to array. Then an object in ArrayList is modified, same way an object is modified in array. As you can see both the changes are reflected in both ArrayList as well as array.

Output

Using toArray() method to convert ArrayList to array

As you can see the converted array is of type Object which is a drawback of using this method.

Converting ArrayList to array without any API methods

You can also convert ArrayList to array in Java by iterating the ArrayList and then assigning elements to array.

That’s all for the topic How to Convert ArrayList to Array in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.