This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

The problem:

How do I convert a list to an array in Java? Check the following code:

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);  
Copy the code

I need to populate the tiendasList values into the Tiendas array.

The popular answer:


Answer 1:

Like this:

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

Or:

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

Note that this only applies to arrays of reference type. For primitive arrays, use the traditional approach:

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

Update: I recommend using list.toarray (new Foo[0]) now; Instead of using list.toarray (new Foo[list.size()]); From JetBrains Intellij Idea Inspection:

There are two styles for converting collections to arrays: using a pre-sized array (such as C.toarray (new String[c.size()]) or using an empty array (such as C.Toarray (new String[0]). In older Versions of Java, pre-sized arrays are recommended because the reflection calls required to create an appropriately sized array are very slow. However, due to the latest update to OpenJDK6, this call is internalized, making the empty array version perform as well as, and sometimes better than, previous versions. Also, passing pre-sized arrays can be dangerous for concurrent or synchronized collections, because there can be data contention between size and toArray calls, and if the collection is simultaneously shrunk during the operation, it can result in an extra null value at the end of the array. This checking allows a uniform style to be followed: either use empty arrays (recommended in modern Java), or use pre-sized arrays (which may be faster in older Java versions or non-hot-flash-based JVMS).Copy the code

Translated from Stack Overflow