DJ_AM_Juicebox
asked on
Using ArrayList.toArray()
Hi,
I'm using java 1.5, how do we use toArray? I have something like:
public class Car
{
int color;
}
ArrayList<Car> cars = new ArrayList<Car>();
cars.add(new Car());
Car[] test = cars.toArray();
Yeah I just need a plain array representation of the array list.
Will the produced array be a reference to the original ArrayList, or is it a completely new object (so changes to one will not affect the other?)
Thanks
I'm using java 1.5, how do we use toArray? I have something like:
public class Car
{
int color;
}
ArrayList<Car> cars = new ArrayList<Car>();
cars.add(new Car());
Car[] test = cars.toArray();
Yeah I just need a plain array representation of the array list.
Will the produced array be a reference to the original ArrayList, or is it a completely new object (so changes to one will not affect the other?)
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
And I see CEHJ already pointed out how to get the array...
FYI, since using the toArray(T[]) method, it already returns an object of type T[] which in this case is Car[]; therefore, the extra cast to (Car[]) is not required.
Car[] test = cars.toArray(new Car[cars.size()]);
Good luck!
FYI, since using the toArray(T[]) method, it already returns an object of type T[] which in this case is Car[]; therefore, the extra cast to (Car[]) is not required.
Car[] test = cars.toArray(new Car[cars.size()]);
Good luck!
But, this works also:
Car[] test = cars.toArray(new Car[0]);
;JOOP!
Car[] test = cars.toArray(new Car[0]);
;JOOP!
As a personal preference, I usually use the List interface to define variable and instantiate ArrayList as the implementation, so my code has that difference but works same with how you have it.
Here is an example code to illustrate what I mean with values.
Open in new window