0

I know there have been many questions similar to this yet I cant find one that helps my problem. I have an Object class, Car, and have a multidimensional array that stores the car objects with the x and y values as coordinates. I want to make a copy of my original array and make changes to the copy array with out changing the values of the original. Here is my code:

public Car[][] copy(Car[][] cars) {

    Car[][] temp = new Car[8][8];

    for (int i = 0 ; i < 8 ; i++) {
        for (int j = 0 ; j < 8 ; j++) {
            temp[i][j] = car[i][j];
        }
    }
    return temp;
}
mike157
  • 63
  • 3
  • 14
  • clone(), present in Object class, might help – Sarthak Mittal Apr 08 '15 at 10:12
  • In your case, you are assigning the same reference to the object on both arrays, so changing one will affect the other. Please refer to the linked question which should shed some light on the copying of objects in Java. You might also want to consider `Deep Copying`. – npinti Apr 08 '15 at 10:14

0 Answers0