Convert ArrayList to Arrays in Java

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

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

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

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


29 Comments

  • Moe Lavigne 3 July, 2009, 6:17

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

  • TinhTruong 3 July, 2009, 7:59

    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]);

  • Moe Lavigne 3 July, 2009, 8:47

    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;

  • Dave 3 July, 2009, 17:26

    Thanks!
    It was useful for me! :)

  • Hauke 4 July, 2009, 20:54

    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]”.

  • Frsutrated 19 March, 2010, 13:39

    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

    • LeszekG 2 October, 2012, 15:44

      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.

  • cristian 20 July, 2010, 5:23

    thanks!!!!!!

  • Ahmad 3 December, 2010, 21:49

    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

  • ram 4 October, 2011, 20:07

    thanks

  • Shakeel 21 March, 2012, 6:07

    This is good way to convert ArrayList to Array

     //this is Generic 
            ArrayList al = new ArrayList();
            al.add("Shakeel");
            al.add("Raj");
            
            //this is collection
            ArrayList al1 = new ArrayList();
          al1.add("Shakeel");
            al1.add("Shaan");
            al1.add("Shakeel");
            al1.add("Raj");
           
                   
            
            //ArrayList to Array
            String ar[]=al.toArray(new String[al.size()]);
            ar=al.toArray(ar);
            for(int j=0;j&lt;ar.length;j++)
            {
                System.out.println(&quot;Element of ar &quot; + ar[j]);
            }
            System.out.println(&quot;&quot;);
            Object ar1[]=al1.toArray(new Object[al1.size()]);
            ar1=al1.toArray(ar1); 
            for(Object e:ar1)
            System.out.println(&quot;Elements of ar1 &quot; +(String) e);
    
  • Dennis meade 13 May, 2012, 21:11

    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

  • Mitul Patel 9 July, 2012, 15:57

    Thanks. Its a very useful to me.

  • sadhana 1 November, 2012, 22:38

    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!!!

  • vidyashree 10 November, 2012, 20:22

    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?

    • Yunus 4 December, 2012, 19:38
      ArrayList<SubCategories> arrSubCategories;
      SubCategories[] subCategoriesData;
      subCategoriesData = arrSubCategories.toArray(new SubCategories[arrSubCategories.size()]);
      

      where in my case SubCategories class is like following :

      public class SubCategories {
      
      	public String item;
      	public String price;
      
      	public SubCategories(){
      		
      	}
      	
      	public SubCategories(String item,String price){
      		super();
      		this.item = item;
      		this.price = price;
      	}
      	
      	public String getItem() {
      		return item;
      	}
      
      	public void setItem(String item) {
      		this.item = item;
      	}
      
      	public String getPrice() {
      		return price;
      	}
      
      	public void setPrice(String price) {
      		this.price = price;
      	}
      

      Hope this is useful to you.. :)

  • Max 12 December, 2012, 5:30

    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! :)

  • Cvenkel Miran 18 December, 2012, 14:37

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

  • ArunM 7 March, 2013, 20:03

    Thanks Viral. Was wondering how I could convert without typecasting

  • Developer 22 March, 2013, 20:42

    Very Useful. Thanks for sharing info.

  • Laramie Crocker 29 March, 2013, 3:10

    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

    • Viral Patel 30 March, 2013, 15:46

      Thanks Laramie, I have fixed the error.

  • divy 3 May, 2013, 10:11

    Nice blog….

  • jay 6 September, 2013, 12:33

    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);
    }

  • wangzhengyi 29 November, 2013, 17:09

    thank you, it’s very useful to me

  • Omor Faruq 18 February, 2014, 9:03

    U R great!

  • Chandran 10 April, 2014, 9:55

    Thanks it was helpful..

  • Dev 4 May, 2014, 20:26

    Thank you. Great post !!

  • Sateesh 13 August, 2014, 20:06

    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

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *