[java] Convert list to array in Java

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.

This question is related to java arrays list arraylist

The answer is


Try this:

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

Object[] ol = list.toArray();

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

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

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


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

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'

An alternative in Java 8:

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

Since Java 11:

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

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.


For ArrayList the following works:

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

//... add values

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

I think this is the simplest way:

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable