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 = new Arrays(Arrays.asList(countries));
System.out.println("ArrayList of Countries:" + list);

Facebook  Twitter      Stumbleupon  Delicious
  

5 Comments on “Convert ArrayList to Arrays in Java”

  • Moe Lavigne wrote on 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 wrote on 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 wrote on 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 wrote on 3 July, 2009, 17:26

    Thanks!
    It was useful for me! :)

  • Hauke wrote on 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]“.

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.