Rabu, 26 Februari 2014

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 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 of 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.




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
























Source:http://javarevisited.blogspot.com/2011/06/converting-array-to-arraylist-in-java.html

Tidak ada komentar:

Posting Komentar