Thursday, June 23, 2011

3 example of converting array to ArrayList and ArrayList to array in Java program

How to change from array to ArrayList and ArrayList to array in java
Have you encountered any situation where you quickly wanted to convert your array to ArrayList or ArrayList to array ? I have faced many such situations which motivate me to write these quick Java tips about converting 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. 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 form of object in either Array or ArrayList or sometime 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 can convert an ArrayList to String into an String array or ArrayList of Integer into an Integer Array. Generics provides 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.



1) 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 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.


2) Array to ArrayList by using Collections.addAll method


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


List 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");

3) 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();
 newAssetList.addAll(Arrays.asList(asset));

These were the three methods to convert an array to arraylist. 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());
System.out.println(currencyList);

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()];
assetTradingArray.
toArray(assetTradingArray);

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.

Related Java Tutorials

6 comments :

Anand said...

Nice One Javin!!!

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

Regards,
Anand.

GeekDude said...

Hi nice explanation..you 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...

Hi,

In Example of converting ArrayList to Array in Java
i think this is declared wrongly..
assetTradingArray.toArray(assetTradingArray);
the correct version is given below..
assetTradingArray.toArray(assetTradingList);

if i may wrong, please tell me

Anonymous said...

Both posts by Javin Paul:
assetTradingArray.toArray(assetTradingArray);
and Vibin Arun:
assetTradingArray.toArray(assetTradingList);
are wrong. The correct one is:
assetTradingList.toArray(assetTradingArray);
Cheers. :)

Aakash Agarwal said...

Exactly.

assetTradingList.toArray(assetTradingArray);

is the correct one. Though I would say that

assetTradingArray = assetTradingList.toArray(assetTradingArray);

is much better.

Post a Comment