582

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.

SDJ
  • 3,622
  • 1
  • 10
  • 30
colymore
  • 9,604
  • 13
  • 45
  • 84

11 Answers11

1199

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

Eng.Fouad
  • 107,075
  • 62
  • 298
  • 390
  • 16
    for the first form I prefer `list.toArray(new Foo[0])` as that makes it clear that the parameter is passed for the type information only and the size is irrelevant. – Marcus Junius Brutus Jul 10 '13 at 19:41
  • 21
    @MarcusJuniusBrutus No, you are wrong. if you are using `new Foo[0]` then you are creating an extra useless array. Check the source code to verify. – Eng.Fouad Jul 10 '13 at 19:46
  • 53
    Why it isn't just `Foo[] array = list.toArray();` is beyond me. – Diederik Dec 04 '13 at 09:46
  • 16
    @Diederik Because `list.toArray()` returns `Object[]` not `Foo[]`. – Powerlord Dec 05 '13 at 19:33
  • 2
    @powerlord that's the nasty unexpected thing. I would have expected it to do the simple and obvious thing. Now the poor developer has the remember lots of java type details, just to get an array out of her ArrayList. :( – Diederik Dec 05 '13 at 19:45
  • 23
    @Diederik It's an unfortunately side effect of Java's Generics collections sharing classes with its non-Generic collections. `Collection`'s `.toArray()` was defined way back in Java 1.0 or 1.1 as returning `Object[]` and it's far too late to change that now. Kinda makes me wish Java used different collections for generics like .NET did to avoid this insanity. – Powerlord Dec 05 '13 at 20:27
  • 2
    @Eng.Fouad You're right, but stop saying 'check the source code' here and in comments on other answers: the information about how the array parameter to `toArray(T[] a)` works is right there in the Java API documentation which any sane person would check first :-) – Stuart Rossiter Jan 22 '15 at 16:36
  • 1
    Coming from a Haskell background, the idea of passing in an array of the correct type seems a really awkward way to give type information to the compiler; but the parameter to `toArray` is not just a type witness; the value is actually used to calculate the value. – jpaugh Dec 07 '15 at 22:04
  • 3
    @Powerlord But something like toTypedArray() could be introduced. – user31389 Jan 12 '16 at 22:13
  • 1
    @Powerlord Is it really? What prevents Java from having a `toTypedArray<>` function on `List`? – John Apr 10 '16 at 21:31
  • @John Nothing *prevents* Java's developers from doing it. They probably don't see a point as you'd have to get the `Class` object then use reflection to create the new array, which is slower than just creating an array and passing it in. – Powerlord Apr 10 '16 at 22:39
  • On a side note, I don't see a link to the JavaDocs for `toArray(T[])` linked yet, so [here's the JavaDocs](http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#toArray-T:A-), which makes it clearer that Java will reuse the array you pass in if it's large enough. Since arrays are a reference type, the value that gets passed for them is a reference. – Powerlord Apr 10 '16 at 22:41
  • @Powerlord Reflection? I really mean just a function `T[] List.toTypedArray()` - perhaps I suggested something else by putting the square brackets behind the symbol. – John Apr 11 '16 at 06:37
  • 1
    @John In Java you cannot instantiate a new array of a generic type (https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java) which would be required in the method for which you describe the header. – klaar Dec 13 '16 at 15:10
  • What would Foo represent? POJO class name? – Jesse Dec 20 '16 at 16:03
  • The Java 8 streams version in @VitaliiFedorenko's answer works for primitive types via `toArray()` in conjunction with `.mapToDouble()` – Joshua Goldberg May 14 '18 at 23:06
  • @Eng.Fouad "For arrays of primitive types, use the traditional way" use stream instead of traditional way int[] array = list.stream().mapToInt(i->i).toArray(); – Mohiul Alam Nov 05 '20 at 20:29
220

An alternative in Java 8:

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

Since Java 11:

String[] strings = list.toArray(String[]::new);
Jacob van Lingen
  • 6,165
  • 3
  • 39
  • 68
Vitalii Fedorenko
  • 97,155
  • 26
  • 144
  • 111
46

I think this is the simplest way:

Foo[] array = list.toArray(new Foo[0]);
Ondrej Slinták
  • 29,278
  • 20
  • 90
  • 124
Fer
  • 485
  • 4
  • 2
  • 4
    Maybe set the correct size of the array, as you obviously know it – Oskar Kjellin Jul 03 '13 at 11:25
  • 7
    ^ No need to set the size of the array if this is the intended style. Documentation for toArray(T[] a): `If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.` – Su Zhang Feb 13 '14 at 03:09
  • 3
    @SuZhang `If the list fits in the specified array`. For sure the list does not fit into the passed array `new Foo[0]` (unless the list itself is empty), and a new array will be created for holding the list items. You are just passing the type of the array (while the object itself is useless). – Eng.Fouad Mar 11 '14 at 11:23
  • 1
    @Eng.Fouad I should have made it clear that I was replying Oskar Kjellin :P – Su Zhang Mar 11 '14 at 17:56
  • 2
    When passing in an array if too small size, the toArray() method has to construct a new array of the right size using reflexion. This has significantly worse performance than passing in an array of at least the size of the collection itself. Source: Intellij's inspection: http://git.jetbrains.org/?p=idea/community.git;a=blob;f=plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/ToArrayCallWithZeroLengthArrayArgumentInspectionBase.java;h=51bee0da98c0f5d529b89f6a7e07352b346ef743;hb=f06ad8a2e893083c9fac3aa4c1cf3ba49b7a84f4 – unify Apr 29 '14 at 20:25
  • @unify Looks like it's actually faster, see [this answer](https://stackoverflow.com/a/4042464/1276306). – flawyte Nov 12 '18 at 13:38
3

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'
Armed10
  • 386
  • 2
  • 6
  • Posting someone else's code that works without any code comments or explanation is not a very compelling answer (but no -1 since it's technically correct). – Stuart Rossiter Jan 22 '15 at 16:37
  • Your comment however causes others to downvote my answer anyway. – Armed10 Jan 23 '15 at 10:07
  • 1
    While technically correct, this solution is redundant; you need either the `(Long[])` cast, or the `new Long[list.size()]` argument to `toArray`, but not both! – jpaugh Dec 07 '15 at 22:11
3

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

pandre
  • 6,335
  • 7
  • 38
  • 48
1

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]);
}
John S.
  • 596
  • 1
  • 3
  • 14
0

For ArrayList the following works:

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

//... add values

Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Hans
  • 1,643
  • 22
  • 15
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
Sk93
  • 3,494
  • 3
  • 33
  • 62
  • 3
    Please don't just copy other people's work as your own, without attribution. http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example – laalto Dec 02 '14 at 10:34
0

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);
}
jpaugh
  • 5,719
  • 4
  • 33
  • 83
-1

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.

  • 19
    You need to check the source code. If you use `new Foo[0]` then the array `new Foo[0]` will be ignored and a new array of a proper size will be created. If you use `new Foo[list.size()]` then the array `new Foo[list.size()]` will be filled and no other array will be created. – Eng.Fouad Sep 29 '13 at 00:53
-5

Try this:

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

Object[] ol = list.toArray();
user
  • 85,380
  • 17
  • 189
  • 186