Convert ArrayList to Array in Java

In Java world, we deal with ArrayList very often. Many times we need to convert ArrayList to Array in Java. Though this is simple task but many people don’t know how to do it. Java ArrayList provides many methods to operate on ArrayList.

ArrayList provides toArray() method to convert an ArrayList to array in Java. The syntax of toArray() method is as follows:

toArray() method returns an array containing all the elements in the list in proper sequence (from first to last element).
This method acts as bridge between array-based and collection-based APIs.

Why we need to convert ArrayList to Array ?

Following are some of the reasons why you want to convert an ArrayList into an Array.

  • To obtain faster processing for certain operations.
  • To integrate collection-based code with legacy code which does not understand collections.

 

Example:

Let’s see how ArrayList can be converted to Array with an example.

If you want to convert an ArrayList of any class into Array, then use the below code where T refers to the class whose arrays you want to create.

The above toArray() method returns an array of elements that have the same type as T. Normally, this form of toArray() method is more convenient because it returns the proper type of array.

We have learned how to convert ArrayList to Array in Java in this tutorial. If you want to convert an Array to ArrayList, then see Convert Array to ArrayList in Java.

Related posts

Leave a Comment