views:

121

answers:

4

Hello,

Is there a command in java for conversion of an ArrayList into a object array. I know how to do this copying each object from the arrayList into the object array, but I was wondering if would it be done automatically.

I want something like this:

ArrayList<TypeA> a;

// Let's imagine "a" was filled with TypeA objects

TypeA[] array = MagicalCommand(a);
+9  A: 

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

Mark E
+4  A: 

Yes. ArrayList has a toArray() method.

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html

Rachel
A: 
TypeA[] array = (TypeA[]) a.toArray();
jweber
toArray without parameters returns an Object[] not a TypeA[]. That code would fail at runtime.
Yishai
You can cast e.g. a `String[]` to `Object[]`, but not vice versa.
Christian Semrau
A: 

You can use this code

ArrayList<TypeA> a = new ArrayList<TypeA>();
Object[] o = a.toArray();

Then if you want that to get that object back into TypeA just check it with instanceOf method.

Shashank T