Skip to content

Converting ArrayList to Array and Array to ArrayList in Java

This quick article is going to show how to convert between an Array and a ArrayList and vice versa.

Convert ArrayList to Array

The toArray() method in ArrayList (Resizable-array implementation of the List interface) returns an array containing all of the elements in this list in proper sequence (from first to last element). The returned array will be “safe” in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array. This method acts as bridge between array-based and collection-based APIs.

Example:

List<String> letters = new ArrayList<>();  
//adding String Objects to letters ArrayList  
letters.add("A");  
letters.add("B");  
letters.add("C");  
letters.add("D");  
letters.add("E");  
System.out.println("Converting ArrayList to Array" );  
String[] lettersArray = letters.toArray(new String[letters.size()]); 

Convert Array to ArrayList

The Arrays class introduced in Java 7 contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.

The toList() method returns a fixed-size list backed by the specified array. This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

This method also provides a convenient way to create a fixed-size list initialized to contain several elements:

Example:

String[] sourceArray = { "Moe", "Jackson", "Petersburg", "Venize" };
List<String> targetList = Arrays.asList(sourceArray);

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.