2

How can I fill a array with the data provided by one List?

For example, I have a List with Strings:

List l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");

then I want to copy this data into a String array:

String[] array = ?

5 Answers 5

11

There's a toArray() method in list...
You have to first allocate an array of an appropriate size (typically list.size()), and then pass it to the toArray method as a parameter. The array will be initialized with the list content.

For example:

String[] myArray = new String[myList.size]();
myList.toArray(myArray);

You can also do the new call inside the parentheses of toArray

Sign up to request clarification or add additional context in comments.

4 Comments

For safety it should be myArray = myList.toArray(myArray);
@Hardcoded: I've always wondered about that one. Why is there even a return type here? I always hate methods that change their input and return it unless you chain them.
The method first checks, if the given array is big enough. If it isn't, a new one will created. The only reason for the array parameter is, that there were no information about the type of the array at runtime. It could have been taken a Class-object as well.
This is minor, but the standard idiom here is to pass in a zero length array of the desired class. If the list contains 0 elements, it will be returned (0 length arrays are immutable and safe to share). If the list is longer than 0 elements, a new array is created. This is cleaner than creating the array up-front with the desired size. So String[] myArray = myList.toArray(new String[0]);
7

First, you have to specify the concrete type of the List - List<String> (don't leave it raw).

Then, you can do

String[] array = list.toArray(new String[list.size()]);

Comments

3

You can use the toArray(T[] a) method:

String[] arr = list.toArray(new String[0]);

Or alternately:

String[] arr = list.toArray(new String[list.size()]);

The difference between the two is that the latter may not need to allocate a new array.


Effective Java 2nd Edition: Item 23: Don't use raw types in new code.

JLS 4.8 Raw Types

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.


Don't make a habit of naming an identifier l. It looks an awful lot like 1.

Comments

2

Syntax is a little goofy; you have to provide your own created array as input.

String[] array = l.toArray(new String[l.size()]);

Comments

1
String[] array = new String[l.size()];
l.toArray(array);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.