Steffan Harris
Steffan Harris

Reputation: 9326

Assign an arraylist to an array in java

Is there anyway I could assign an arrayList to an array in Java?

Upvotes: 2

Views: 2918

Answers (3)

jbindel
jbindel

Reputation: 5635

Object[] array = myArrayList.toArray(new Object[myArrayList.size()]);?

Upvotes: 2

Topera
Topera

Reputation: 12389

Yes, use toArray() in List.

See:

  List a = new ArrayList();
  a.add("foo");
  a.add("bar");
  System.out.println(a); // prints [foo, bar]

  Object[] myArray = a.toArray();
  for (int i = 0; i < myArray.length; i++) {
   System.out.println(myArray[i]); // prints 'foo' and 'bar'
  }

See online, in ideone.

Upvotes: 11

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

Call List.toArray()

Upvotes: 0

Related Questions