marionmaiden
marionmaiden

Reputation: 3360

Fill a array with List data

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 = ?

Upvotes: 2

Views: 11610

Answers (5)

polygenelubricants
polygenelubricants

Reputation: 383716

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.

Upvotes: 3

Ben Zotto
Ben Zotto

Reputation: 71008

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

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

Upvotes: 2

Roman
Roman

Reputation: 66156

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

Upvotes: 1

Bozho
Bozho

Reputation: 597036

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

Upvotes: 7

Uri
Uri

Reputation: 89729

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

Upvotes: 10

Related Questions