Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
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
 
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Java is pass by value, but for objects what you are passing by value is the reference to Object itself so change in a Car from array will change value in Car of List, etc.

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.
public static void main(String[] args) {
		List<Car> cars  = new ArrayList<Car>();
	    cars.add(new Car());
 
	    Car[] test = cars.toArray(new Car[cars.size()]);
	    Car[] test2 = cars.toArray(test);
	    
	    test[0].color = 1;
	    System.out.println(test[0].color);
	    
	    test2[0].color = 3;
	    System.out.println(test2[0].color);
	    
	    cars.get(0).color = 7;
	    
	    System.out.println(test[0].color);
	    System.out.println(test2[0].color);
	    System.out.println(cars.get(0).color);
	}

Open in new window

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!
Avatar of sciuriware
sciuriware

But, this works also:

                                  Car[] test = cars.toArray(new Car[0]);

;JOOP!