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()]);
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)
Get our Articles via Email. Enter your email address.

You may also like...

34 Comments

  1. Moe Lavigne says:

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

  2. TinhTruong says:

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

  3. Moe Lavigne says:

    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;

  4. Dave says:

    Thanks!
    It was useful for me! :)

  5. Hauke says:

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

  6. Frsutrated says:

    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 says:

      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.

  7. cristian says:

    thanks!!!!!!

  8. Ahmad says:

    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

  9. ram says:

    thanks

  10. Shakeel says:

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

  11. Dennis meade says:

    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

  12. Mitul Patel says:

    Thanks. Its a very useful to me.

  13. sadhana says:

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

  14. vidyashree says:

    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 says:

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

  15. Max says:

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

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

  17. ArunM says:

    Thanks Viral. Was wondering how I could convert without typecasting

  18. Developer says:

    Very Useful. Thanks for sharing info.

  19. Laramie Crocker says:

    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.

  20. divy says:

    Nice blog….

  21. jay says:

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

  22. wangzhengyi says:

    thank you, it’s very useful to me

  23. Omor Faruq says:

    U R great!

  24. Chandran says:

    Thanks it was helpful..

  25. Dev says:

    Thank you. Great post !!

  26. Sateesh says:

    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

  27. ivan says:

    thank you so much

  28. Naren says:

    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 ?

  29. T4Tester says:

    How to convert int []x = {3,2,1,3,2,1,4,3,5,3} to Set ?

  30. arun says:

    Thank you.It was useful to me

  31. This makes it more clear now. thanks.

Leave a Reply

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