Java ArrayList to Array

Java ArrayList to Array

Java ArrayList to Array

Summary: After seeing the 4 styles of converting array elements into array list, now let us do the opposite way of converting "Java ArrayList to Array".

Note: There are two methods, asList() and toArray(), that bridges collection classes (data structures) and array. These methods are defined in Arrays class and Collection interface (inherited by List interface).

The following program illustrates toArray() method in converting Java ArrayList to Array.

Java ArrayList to Array

An array list object al1 is created and added 3 elements with add() method.

The toArray() method of List (inherited from Collection interface) interface returns an Object array with all the elements of array list al1. Using the enhanced for loop (commonly known as foreach loop), all the elements of the array are printed.

Alternatively, the above for loop can be avoided using toString() method of Arrays class to print the elements of the array (not shown in the program).

The Object array can be converted into a string array as follows, if required in the code.

Explicit casting is done to convert object of Object class to String class.

Array related topics that increase array manipulation techniques

Java comes with many classes grouped as categories. Would you like to know?

Pass your suggestions to improve the quality of this tutorial "Java ArrayList to Array".

Leave a Reply

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