Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an ArrayList to an object array

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); 
like image 727
marionmaiden Avatar asked Apr 30 '10 14:04

marionmaiden


People also ask

Can we convert list to object in Java?

Yes. ArrayList has a toArray() method.

How do you convert an array to an object in Java?

Converting an array to Set object The Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.

Can you make an ArrayList of objects?

You can simply use add() method to create ArrayList of objects and add it to the ArrayList. This is simplest way to create ArrayList of objects in java.


1 Answers

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[])

like image 150
Mark Elliot Avatar answered Oct 24 '22 19:10

Mark Elliot