Sei sulla pagina 1di 4

39/17/12

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

Javarevisited
Blog about Java Program Tutorial Example How to, Unix Linux commands, Interview Questions, FIX Protocol, Tibco RV tutorials, Equities trading system, MySQL
Ads by Google Java Java Class Java Developer Java Tutorial

T H UR S DA Y , J UNE 23, 2011 Searc h

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


Recent Posts
How to change from array to ArrayList and ArrayList to
array in java What is EnumMap in Java – Example Tutorial
Have you encountered any situation where you quickly wanted to
Difference between save vs persist and
convert your array to ArrayList or ArrayList to array ? I have faced
saveOrUpdate in Hibernate
many such situations which motivate me to write these quick Java
tips about converting array to ArrayList and ArrayList to array in How to replace escape XML special characters in
Java. Both array and ArrayList are quite common and every Java
Java String
developer is familiar with this. Former is used to store object and Java program to find IP Address of localhost -
primitive type while later can only hold objects. Array is part of Example Tutorial
standard Java fundamental data structure while ArrayList is Top 10 JDBC Best Practices for Java Programmer
part of collection framework in Java. Most of the time we store data
How to delete empty files directories in Unix Linux
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 How to Convert Collection to String in Java -
one array to ArrayList or ArrayList to array in Java. This short array Spring Framework Example
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.Arraysclass 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. Follow Us
4) Another important point is since List is fixed size, you can not add element into it. If you try you will get exception. Follow @javinpaul 749 follow ers
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.
Javarevisited on Follow

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 +523
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.

javarevisited.blogspot.sg/2011/06/converting-array-to-arraylist-in-java.html 1/4
39/17/12
example of converting array to ArrayList and ArrayList to array in Java program

Javarevisited on Facebook
List assetList = new ArrayList();
String[] asset = {"equity", "stocks", "gold", Like
"foriegn exchange", "fixed income", "futures",
"options"}; 1,056 people like Javarevisited.

Collections.addAll(assetList, asset);

Kaly an A maresh S atish A nil A nkur

Important point about this method of array to ArrayList conversion F acebook social plugin
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. Subscribe by email:

Subscribe
Arraylist newAssetList = new Arraylist(); By Javin Paul
newAssetList.addAll(Arrays.asList(asset));
Subscribe To This Blog Free
These were the three methods to convert an array to arraylist. You can also create arrays of ArrayList because list can
Posts
hold any type of object.
Comments

Array to List in Java using Spring Framework Followers


There is another easy way of converting array to ArrayListif you are using spring framework. spring framework
Join this site
provides several utility method in class CollectionUtils, one of the is CollectionUtils.arrayToList()which can
w ith Google Friend Connect
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 Listreturned by Arrays.asList(),You Members (575) More »
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 Already a member? Sign in

//currencyList.remove("GBP");//Exception in thread "main"


java.lang.UnsupportedOperationException Ads by Google

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

How to convert ArrayList to Array in Java Blog Archive

► 2012 (139)
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 ▼ 2011 (145)
it’s simpler than you have probably thought again we have java.util.Arraysclass as our rescue. This class acts as ► December (28)
bridge between ArrayList to array. ► November (14)
► October (14)
Example of converting ArrayList to Array in Java ► September (22)
In this example of arraylist to array we will convert our assetTradingList into String array.
► August (11)
► July (7)
ArrayList assetTradingList = new ArrayList(); ▼ June (9)
List of special bash parameter used in Unix or
assetTradingList.add("Stocks trading"); Li...
assetTradingList.add("futures and option trading"); 3 example of converting array to ArrayList and
assetTradingList.add("electronic trading"); Arr...
assetTradingList.add("forex trading"); 10 example of using Vim or VI editor in UNIX
assetTradingList.add("gold trading"); and L...

javarevisited.blogspot.sg/2011/06/converting-array-to-arraylist-in-java.html 2/4
39/17/12
example of converting array to ArrayList and ArrayList to array in Java program
assetTradingList.add("fixed income bond trading"); 3 ways to resolve NoClassDefFoundError in Java
String [] assetTradingArray = new String[assetTradingList.size()]; How to use Comparator and Comparable in
assetTradingArray.toArray(assetTradingArray); Java? With...
10 examples of grep command in UNIX and
After execution of last line our assetTradingList will be converted into String array. If you like to learn more about How Linux
to use ArrayList in Java efficiently check the link it has details on all popular operation on Java arraylist.
Top 30 Programming questions asked in
Interview - ...
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
Tibco tutorial : Reliability Parameter Explained
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 How Volatile in Java works ? Example of volatile
k...
converting from arraylist to array and vice-versa.
► May (6)
Related Java Tutorials
► April (10)
How to Solve Java.lang.OutOfMemoryError: Java Heap Space
How to Solve UnSupportedClassVersionError in Java ► March (4)
Example of Polymorphism in Java ► February (10)
What is abstraction in Java with Example
► January (10)
How to Split String in Java
How to Convert String to Date in Java ► 2010 (33)
How to Convert Integer to String in Java

eXo Cloud IDE


Code In the Cloud, Deploy in the Cloud! References
www.cloud-ide.com Java API documentation JDK 6
Spring framework doc
Please share with your friends if like this article
Struts
ANT
Maven
RECOMMENDED FOR YOU ? × JDK 7 API
Futures and option trading Forex Trading Foriegn Exchange Stocks Trade
What is EnumMap in Java – Example Tutorial MySQL
Linux
You might like:
Like 0 Tw eet 0 Eclipse
10 Object Oriented Design principles Java programmer should know
Top 10 Collection Interview Questions Answers in Java Copyright by Javin Paul 2012. Powered by Blogger.
How Synchronization works in Java ? Example of synchronized block
How to Set Classpath for Java on Windows Unix and Linux

Posted by Javin Paul at 6:23 AM +4 Recommend this on Google

Labels: core java, core java interview question, java collection tutorial

Tag Cloud

Free online writing courses Website design tutorial Mutual Fund


Online Classes Forex Brokers Forex Trading
4 comments:

Anand said...
Nice One Javin!!!

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

Regards,
Anand.

June 29, 2011 6:12 AM

GeekDude said...
Hi nice explanation..you can find the ArrayList to HashSet Conversion here....

ArrayList to HashSet

July 4, 2011 11:11 PM

sudhansu(Gm Odihsa) said...


It is very nice coding.but any one only use in-built method.but without in-built method plz do it....

November 15, 2011 9:19 AM

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

javarevisited.blogspot.sg/2011/06/converting-array-to-arraylist-in-java.html 3/4
39/17/12
example of converting array to ArrayList and ArrayList to array in Java program
Arary in Java you need to rely on other examples like adding individual array element etc.

March 20, 2012 8:10 PM

Post a Comment

Enter your comment...

Comment as: Google Account

Publish Preview

Newer Post Home Older Post

Subscribe to: Post Comments (Atom)

About Me Privacy Policy

javarevisited.blogspot.sg/2011/06/converting-array-to-arraylist-in-java.html 4/4

Potrebbero piacerti anche