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 that 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 objects and primitive types while later can only hold objects. The array is part of standard Java fundamental data structure while ArrayList is part of the 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 a situation don't bother just remember these tips and you will get through it. If you compare array vs ArrayList only significant difference is one is fixed size while the 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 in descending order.
On related not from Java 5 onwards, ArrayList class supports Generics in Java, which means you can convert an ArrayList of String into a String array or ArrayList of Integer into an Integer Array. The generic provide type safety and remove casting during runtime.
So you can say the former is fixed-size and you later are re-sizable. java.util.Arrays class act as a bridge between array to ArrayList and is 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.
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 that 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 objects and primitive types while later can only hold objects. The array is part of standard Java fundamental data structure while ArrayList is part of the 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 a situation don't bother just remember these tips and you will get through it. If you compare array vs ArrayList only significant difference is one is fixed size while the 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 in descending order.
On related not from Java 5 onwards, ArrayList class supports Generics in Java, which means you can convert an ArrayList of String into a 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? Example
In the first section of this Java tutorial, we will see how to convert from Array to ArrayList while in the second section we will see the opposite of it i.e. from ArrayList to Array. The main difference between these two is that once declared you can not change the size of the former while later is dynamic which re-sizes itself whenever its capacity crossed the threshold specified by the load factor.So you can say the former is fixed-size and you later are re-sizable. java.util.Arrays class act as a bridge between array to ArrayList and is 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<String> assetList = Arrays.asList(asset);
Its worth noting the following point while using Arrays.asList() method for array to arraylist conversion:
1) This method returns a List view of the 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 the 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 points related to the 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
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);
An important point about this method of the 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 the 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 the 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 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 an array to ArrayList if you are using the spring framework. spring framework provides several utility methods in class CollectionUtils, one of the is CollectionUtils.arrayToList() which can convert an array into List as shown in below example of the 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 methods to convert an ArrayList into comma-separated String in Java.
After execution of the last line, our assetTradingList will be converted into a 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 operations on Java ArrayList.
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? Example
Now, this is the opposite side of the 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 the 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()]; assetTradingList.toArray(assetTradingArray);
After execution of the last line, our assetTradingList will be converted into a 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 operations 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 an array to ArrayList are by no means complete and please share your own ways of converting from ArrayList to array and vice-versa.
If you are preparing for a Java interview, don't forget to check my list of Top 25 Java Collection framework interview questions for experienced programmers.
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.
7 comments :
Nice One Javin!!!
Basic Details about the ArrayList in Java can be found by clicking here
Regards,
Anand.
Hi nice explanation..you can find the ArrayList to HashSet Conversion here....
ArrayList to HashSet
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.
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
Both posts by Javin Paul:
assetTradingArray.toArray(assetTradingArray);
and Vibin Arun:
assetTradingArray.toArray(assetTradingList);
are wrong. The correct one is:
assetTradingList.toArray(assetTradingArray);
Cheers. :)
Exactly.
assetTradingList.toArray(assetTradingArray);
is the correct one. Though I would say that
assetTradingArray = assetTradingList.toArray(assetTradingArray);
is much better.
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