A lot of time I have to convert ArrayList to Arrays in my Java program. Although this is a simple task, many people don’t know how to do this and end up in iterating the java.util.ArrayList to convert it into arrays. I saw such code in one of my friends work and I thought to share this so that people don’t end up writing easy thing in complicated way. ArrayList class has a method called toArray() that we are using in our example to convert it into Arrays. Following is simple code snippet that converts an array list of countries into string array.
List<String> list = new ArrayList<String>();
list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");
String [] countries = list.toArray(new String[list.size()]);
Code language: Java (java)
So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
Code language: Java (java)
Convert Array to ArrayList
We just saw how to convert ArrayList in Java to Arrays. But how to do the reverse? Well, following is the small code snippet that converts an Array to ArrayList:import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
...
String[] countries = {"India", "Switzerland", "Italy", "France"};
List list = Arrays.asList(countries);
System.out.println("ArrayList of Countries:" + list);
Code language: Java (java)
The above code will work great. But list object is immutable. Thus you will not be able to add new values to it. In case you try to add new value to list, it will throw UnsupportedOperationException. Related: Resolve UnsupportedOperationException exception Thus simply create a new List from that object. See below:String[] countries = {"India", "Switzerland", "Italy", "France"};
List list = new ArrayList(Arrays.asList(countries));
System.out.println("ArrayList of Countries:" + list);
Code language: Java (java)
String[] countries = new String[0];
List list = new ArrayList();
list.add(“India”);
list.add(“Switzerland”);
list.add(“Italy”);
list.add(“France”);
countries = list.toArray(countries);
You don’t have to put the list.size() to the new array, just 0 is enough because it just uses the information about the type of the return array, not the size, so the following code will work:
T [] countries = list.toArray(new T[0]);
Maybe the following comment would have been better:
This is also works: T[] countries = list.toArray(new T[0]);
The \"toArray\" method automatically adjusts the size of the target array, but it must be initialized… I just use zero;
Thanks!
It was useful for me! :)
If you use an array with the correct size within the toArray method, the result is returned within the provided array. If you use a “new T[0]” another array has to be created, that is thrown away after the type information is read.
So it is bad style to use “new T[0]”.
If your code works then can you please explain this?
Test.java:8: generic array creation
T [] countries = list.toArray(new T[list.size()]);
^
1 error
Instead of T in your code (because there is no such type) put any object type as you want, for example
String [] countries = list.toArray(new String[list.size()]);
It was kind of shortcoming. If you put code with T inside of generic method or class it will works.
thanks!!!!!!
Thank you for the great post.
Maybe, it’s too late to say this but anyway, let’s try.
About the Array to ArrayList conversion, I got error. It cannot recognize the Arrays type.
Obviously, I imported the needed classes but even the NetBeans auto-complete couldn’t help to find the reason of the error!
By a little bit searching, I figured out that the following code works fine:
String[] countries = {“India”, “Switzerland”, “Italy”, “France”};
ArrayList list = new ArrayList(Arrays.asList(countries));
Thanks,
Ahmad
thanks
This is good way to convert ArrayList to Array
I’ve been wanting to use .toArray() for awhile, but could never figure out the syntax.. Now I can use it. In my opinion, Sun did a terrible job of documenting generics.
Thanks
Thanks. Its a very useful to me.
I agree with dennis.Even I couldn’t figure out the way to use toArray() in generics straight forward. This post helped to figure that out. Thank You!!!
i have one doubt see arrays can store only similar types of data if collection contain different types of data like objects thn if we convert to array hw it is converted pls tel me if u know?
where in my case SubCategories class is like following :
Hope this is useful to you.. :)
Thank you, that is very useful … I never initialized the arrays with the right size and, of course, it did not work and they used .toArray() instead, but now I know how to do it right! :)
Sorting does not work in case of string:
“Trnkoczyjeve kričistilne jagode”
note the “č” character.
I would apprecaite a tip, where to modify ColumnComparator class to get this to work.
Note, “č” comes here in alphabet: abcčdefg….
Thanks Viral. Was wondering how I could convert without typecasting
Very Useful. Thanks for sharing info.
Hi,
Thanks for your post. Small syntax error has crept into your example code on the main part of the post:
String[] countries = {“India”, “Switzerland”, “Italy”, “France”};
List list = new Arrays(Arrays.asList(countries));
This won’t compile because you can’t (and don’t want to) call new Arrays(). It is a helper class, with static functions. It is sufficient to say:
List list = Arrays.asList(countries);
Thanks,
Laramie
Thanks Laramie, I have fixed the error.
Nice blog….
this is much is enough guys…………..
int[] d = new int[list.size()];
for(int i=0;i<list.size();i++){
d[i] = list.get(i);
}
thank you, it’s very useful to me
U R great!
Thanks it was helpful..
Thank you. Great post !!
List prepareIssueMonitorMasterList = new ArrayList();
I have some IssueMonitorMaster added to list.
Now i am converting the above list to IssueMonitorMaster[] by using below code
IssueMonitorMaster[] issueMonitorMasterArray = prepareIssueMonitorMasterList.toArray(new IssueMonitorMaster[prepareIssueMonitorMasterList.size()]);
I am getting StackOverflowError
I am struggling from 2 days can some one please help me
thank you so much
Hi, I have a need like this
InterfaceXYZ list = new ArrayList(); // I am using Java 7.
InterfaceXYZ [] countries = list.toArray(new T[list.size()]); ==> This is giving me compile time error. I want to create an array with InterfaceXYZ and return as this array. How to do it ?
How to convert int []x = {3,2,1,3,2,1,4,3,5,3} to Set ?
Thank you.It was useful to me
This makes it more clear now. thanks.