I was wondering whether the copyOf
method in the Arrays class creates new objects which it then passes onto the copied array or just creates new variables that refer to the existing objects. I had tried to construct a bit of code that tests this:
import java.awt.Point;
import java.util.Arrays;
public class PointTest2 {
public static void main(String[] args) {
Point[] array1 = new Point[2];
Point[] array2 = new Point[2];
for(int i = 0; i < array1.length; i++) {
array1[i] = new Point(i, i);
}
array2 = Arrays.copyOf(array1, 2);
array1[0] = array1[1];
array1[1] = array2[0];
System.out.println(Arrays.toString(array1));
System.out.println(Arrays.toString(array2));
System.out.println(array1[0] == array2[1]);
}
}
This program returns:
[java.awt.Point[x=1,y=1], java.awt.Point[x=0,y=0]]
[java.awt.Point[x=0,y=0], java.awt.Point[x=1,y=1]]
true
It seems that if copyOf
only passed references then the resulting arrays should have both elements being a reference to a point object with x = 1
and y = 1
. However, I would think that if the copied array were given new copies of the objects then the equals operator should return false since the references should be different. Can someone help me understand what is going on here? Thanks in advance!