Convert list to array in Java

JavaArraysListArraylist

Java Problem Overview


How can I convert a List to an Array in Java?

Check the code below:

ArrayList<Tienda> tiendas;
List<Tienda> tiendasList; 
tiendas = new ArrayList<Tienda>();

Resources res = this.getBaseContext().getResources();
XMLParser saxparser =  new XMLParser(marca,res);

tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();

this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);  

I need to populate the array tiendas with the values of tiendasList.

Java Solutions


Solution 1 - Java

Either:

Foo[] array = list.toArray(new Foo[0]);

or:

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

Update:

It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.

From JetBrains Intellij Idea inspection:

> There are two styles to convert a collection to an array: either using > a pre-sized array (like c.toArray(new String[c.size()])) or > using an empty array (like c.toArray(new String[0]).

In > older Java versions using pre-sized array was recommended, as the > reflection call which is necessary to create an array of proper size > was quite slow. However since late updates of OpenJDK 6 this call > was intrinsified, making the performance of the empty array version > the same and sometimes even better, compared to the pre-sized > version. Also passing pre-sized array is dangerous for a concurrent or > synchronized collection as a data race is possible between the > size and toArray call which may result in extra nulls > at the end of the array, if the collection was concurrently shrunk > during the operation.

This inspection allows to follow the > uniform style: either using an empty array (which is recommended in > modern Java) or using a pre-sized array (which might be faster in > older Java versions or non-HotSpot based JVMs).

Solution 2 - Java

An alternative in Java 8:

String[] strings = list.stream().toArray(String[]::new);

Since Java 11:

String[] strings = list.toArray(String[]::new);

Solution 3 - Java

I think this is the simplest way:

Foo[] array = list.toArray(new Foo[0]);

Solution 4 - Java

Best thing I came up without Java 8 was:

public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
    if (list == null) {
        return null;
    }

    T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
    list.toArray(listAsArray);
    return listAsArray;
}

If anyone has a better way to do this, please share :)

Solution 5 - Java

I came across this code snippet that solves it.

//Creating a sample ArrayList 
List<Long> list = new ArrayList<Long>();

//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);

//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);

//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);

The conversion works as follows:

  1. It creates a new Long array, with the size of the original list
  2. It converts the original ArrayList to an array using the newly created one
  3. It casts that array into a Long array (Long[]), which I appropriately named 'array'

Solution 6 - Java

This is works. Kind of.

public static Object[] toArray(List<?> a) {
	Object[] arr = new Object[a.size()];
	for (int i = 0; i < a.size(); i++)
		arr[i] = a.get(i);
	return arr;
}

Then the main method.

public static void main(String[] args) {
	List<String> list = new ArrayList<String>() {{
		add("hello");
		add("world");
	}};
	Object[] arr = toArray(list);
	System.out.println(arr[0]);
}

Solution 7 - Java

For ArrayList the following works:

ArrayList<Foo> list = new ArrayList<Foo>();

//... add values

Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);

Solution 8 - Java

Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example

import java.util.ArrayList;
 
public class CopyElementsOfArrayListToArrayExample {
 
  public static void main(String[] args) {
    //create an ArrayList object
    ArrayList arrayList = new ArrayList();
   
    //Add elements to ArrayList
    arrayList.add("1");
    arrayList.add("2");
    arrayList.add("3");
    arrayList.add("4");
    arrayList.add("5");
   
    /*
      To copy all elements of java ArrayList object into array use
      Object[] toArray() method.
    */
   
    Object[] objArray = arrayList.toArray();
   
    //display contents of Object array
    System.out.println("ArrayList elements are copied into an Array.
                                                  Now Array Contains..");
    for(int index=0; index < objArray.length ; index++)
      System.out.println(objArray[index]);
  }
}
 
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5

Solution 9 - Java

You can use toArray() api as follows,

ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);

Values from the array are,

for(String value : stringList)
{
	System.out.println(value);
}

Solution 10 - Java

This (Ondrej's answer):

Foo[] array = list.toArray(new Foo[0]);

Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.

Solution 11 - Java

Try this:

List list = new ArrayList();
list.add("Apple");
list.add("Banana");

Object[] ol = list.toArray();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncolymoreView Question on Stackoverflow
Solution 1 - JavaEng.FouadView Answer on Stackoverflow
Solution 2 - JavaVitalii FedorenkoView Answer on Stackoverflow
Solution 3 - JavaFerView Answer on Stackoverflow
Solution 4 - JavapandreView Answer on Stackoverflow
Solution 5 - JavaArmed10View Answer on Stackoverflow
Solution 6 - JavaJohn S.View Answer on Stackoverflow
Solution 7 - JavaHansView Answer on Stackoverflow
Solution 8 - JavaMUSTKEEM MANSURIView Answer on Stackoverflow
Solution 9 - JavaLearning ProgrammingView Answer on Stackoverflow
Solution 10 - JavaManny VellonView Answer on Stackoverflow
Solution 11 - JavaSheetal PatelView Answer on Stackoverflow