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);
Yes. ArrayList has a toArray() method.
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.
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.
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[])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With