Thursday, June 23, 2011

3 Exampls to Convert an Array to ArrayList in Java

How to convert an array to ArrayList in Java
Have you encountered any situation where you quickly wanted to convert your array to ArrayList or ArrayList to array in Java? I have faced many such situations which motivate me to write these quick Java tips about converting an array to ArrayList and ArrayList to array in Java. Both array and ArrayList are quite common and every Java developer is familiar with this. Former is used to store object and primitive type while later can only hold objects. The array is part of standard Java fundamental data structure while ArrayList is part of collection framework in Java. Most of the time we store data in the form of an object in either Array or ArrayList or sometimes we find either of them suitable for processing and we want to convert from one array to ArrayList or ArrayList to array in Java.

This short array to ArrayList tutorial in Java will explain how quickly you can convert data from each other. So when you face such situation don't bother just remember this tips and you will get through it. If you compare array vs ArrayList only significant different is one is fixed size while other is not.

This article is in continuation of my post Difference between Vector and ArrayList in Java and how to Sort ArrayList in Java on descending order.

On related not from Java 5 onwards, ArrayList class supports Generics in Java, which means you ca convert an ArrayList of String into an String array or ArrayList of Integer into an Integer Array. The generic provide type safety and remove casting during runtime.

How to convert Array to ArrayList in Java

In first section of this Java tutorial we will see how to convert from Array to ArrayList while in second section we will see opposite of it i.e. from ArrayList to Array. Main difference between these two is that once declared you can not change the size of former while later is dynamic which re-sizes itself whenever its capacity crossed threshold specified by load factor.

So you can say former is fixed-size and you later are re-sizable. java.util.Arrays class act as a bridge between array to ArrayList  and used to convert from array to ArrayList or ArrayList  to array. If you like to learn more about Array you may check How to detect if Array contains duplicate or not and How to sort Array elements in Java in ascending order.

Using Arrays.asList() method

Look at the below example, we have an array which contains different kind of asset class e.g. equity, gold and foreign exchange etc and we want to convert into an arraylist. This is the simplest way of converting from array to ArrayList.

String[] asset = {"equity", "stocks", "gold", "foreign exchange","fixed income", "futures", "options"}; 
List<String> assetList = Arrays.asList(asset); 

Its worth to note following point while using Arrays.asList() method for array to arraylist conversion:

1) This method returns a List view of underlying array.

2) List returned by this method would be fixed size.

3) Most important point to note is when you change an element into this List corresponding element in original array will also be changed.

4) Another important point is since List is fixed size, you can not add element into it. If you try you will get exception.

5) This is the most efficient way of converting array to arraylist as per my knowledge because it doesn't copy the content of underlying array to create list.

6) From Java 5 or JDK 1.5 onwards this method supports generic so you can generate type safe ArrayList from array. to know more about Generic see my post How Generic works in Java

One of the most important point related to Arrays.asList() method is that it returns a fixed size List not a read only List, although you can not add() or remove() elements on this List you can still change existing elements by using set method. If you are using this to create read only List than its wrong, Use Collections.unmodifiableList method to create read only collection in Java.

Array to ArrayList by using Collections.addAll method

convert array to arraylist in Java program
This example of converting an array to ArrayList is not that efficient as the earlier method but its more flexible.

List<String> assetList = new ArrayList();
String[] asset = {"equity", "stocks", "gold", "foriegn exchange", "fixed income", "futures", "options"}; 

Collections.addAll(assetList, asset);

Important point about this method of array to ArrayList conversion is :

1) Its not as fast as Arrays.asList() but more flexible.

2) This method actually copies the content of the underlying array into ArrayList provided.

3) Since you are creating copy of original array, you can add, modify and remove any element without affecting original one.

4) If you wan to provide individual element you can do so by specifying them individually as comma separated. Which is a very convenient way of inserting some more elements into existing list for example we can add some more asset classes into our existing assetlist as below?
Collections.addAll(assetList, "Equity Derivatives", "Eqity Index Arbitrage" , "Mutual Fund");

Example of Converting ArrayList to Array using Collection's addAll method

This is another great way of converting an array to ArrayList. We are essentially using Collection interface's addAll() method for copying content from one list to another. Since List returned by Arrays.asList() is fixed-size it’s not much of use, this way we can convert that into proper ArrayList.

Arraylist newAssetList = new Arraylist();

These were the three methods to convert an array to ArrayList in Java. By the way, you can also create arrays of ArrayList because list can hold any type of object.

Array to List in Java using Spring Framework

There is another easy way of converting array to ArrayList if you are using spring framework. spring framework provides several utility method in class CollectionUtils, one of the is CollectionUtils.arrayToList() which can convert an array into List as shown in below example of array to List conversion using spring framework. It’s worth noting though List returned by arrayToList() method is unmodifiable just like the List returned by Arrays.asList(), You can not add() or remove() elements in this List. Spring API also provides several utility method to convert an ArrayList into comma separated String in Java.

String [] currency = {"SGD", "USD", "INR", "GBP", "AUD", "SGD"};
System.out.println("Size of array: " + currency.length);
List<String> currencyList = CollectionUtils.arrayToList(currency);
//currencyList.add("JPY"); //Exception in thread "main" java.lang.UnsupportedOperationException
//currencyList.remove("GBP");//Exception in thread "main" java.lang.UnsupportedOperationException

System.out.println("Size of List: " + currencyList.size());

How to convert ArrayList to Array in Java

Now this is a opposite side of story where you want to convert from Arraylist to Array, instead of array to ArrayList, interesting right. Just now we were looking at converting array to arraylist and now we need to back to former one. Anyway it’s simpler than you have probably thought again we have java.util.Arrays class as our rescue. This class acts as bridge between ArrayList to array.

Example of converting ArrayList to Array in Java

In this example of ArrayList to array we will convert our assetTradingList into String array.
ArrayList assetTradingList = new ArrayList(); 

assetTradingList.add("Stocks trading");
assetTradingList.add("futures and option trading");
assetTradingList.add("electronic trading");
assetTradingList.add("forex trading");
assetTradingList.add("gold trading");
assetTradingList.add("fixed income bond trading");
String [] assetTradingArray = new String[assetTradingList.size()];

After execution of last line our assetTradingList will be converted into String array. If you like to learn more about How to use ArrayList in Java efficiently check the link it has details on all popular operation on Java ArrayList.

Getting a clear idea of converting array to ArrayList and back to ArrayList and array saves a lot of time while writing code. It’s also useful if you like to initialize your ArrayList with some default data or want to add some elements into your existing ArrayList. these examples of converting array to ArrayList is by no means complete and please share your own ways of converting from ArrayList to array and vice-versa. If you are preparing for Java interview, don't forget to check my list of Top 25 Java Collection framework interview questions for experienced programmers.

Further Reading
Java Fundamentals: The Java Language by Jim Wilson
Java Fundamentals: Collections
Head First Java

Other Java Collection tutorials you may like
How to sort a Map by keys and values in Java? (tutorial)
How to sort an ArrayList in ascending and descending order in Java? (tutorial)
Difference between ArrayList and HashSet in Java? (answer)
The difference between TreeMap and TreeSet in Java? (answer)
The difference between HashMap and ConcurrentHashMap in Java? (answer)
The difference between HashMap and LinkedHashMap in Java? (answer)
The difference between Hashtable and HashMap in Java? (answer)
The difference between HashSet and TreeSet in Java? (answer)
The difference between ArrayList and LinkedList in Java? (answer)
The difference between Vector and ArrayList in Java? (answer)
Difference between EnumMap and HashMap in Java

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or feedback then please drop a comment.


Anand said...

Nice One Javin!!!

Basic Details about the ArrayList in Java can be found by clicking here


GeekDude said...

Hi nice can find the ArrayList to HashSet Conversion here....

ArrayList to HashSet

Anonymous said...

I agree for constructing arraylist from array in java, Arrays.asList() is best choice but constructed List here is immutable and it doesn't allow add() or remove() elements from List. If you want to construct proper List from Arary in Java you need to rely on other examples like adding individual array element etc.

Vibin Arun said...


In Example of converting ArrayList to Array in Java
i think this is declared wrongly..
the correct version is given below..

if i may wrong, please tell me

Anonymous said...

Both posts by Javin Paul:
and Vibin Arun:
are wrong. The correct one is:
Cheers. :)

Aakash Agarwal said...



is the correct one. Though I would say that

assetTradingArray = assetTradingList.toArray(assetTradingArray);

is much better.

Anonymous said...

The first method mentioned here is the best way to convert an array to ArrayList in Java because it is fast, doesn't take extra memory and just provide a List view over array. So if you just need a read only view of array as List, this is the one you should use, but if your intention is to modify the list or add, remove new elements then this will not work, because it's a fixed size ArrayList, it cannot grow dynamically.

In order to create dynamic ArrayList form array, simply use new ArrayList(Arrays.asList(array)). this will create a new object of ArrayList and copies element from array to list, which means you can change, add or remove new elements without affecting original array. The third way, which uses Collections.addAll() method is essentiall the same way, because it also copies content from array to list.

Post a Comment