I found an easy-to-understand explanation for clone ()
in Java arrays, so I translated it.
[Quote] stackoverflow Clone method for Java arrays
When the clone method is called on an array, it returns a new instance of the same array element.
For example, the following code creates different instances for ʻint [] a and ʻint [] b
.
int[] a = {1,2,3};
int[] b = a.clone();
* 「a == b ?Is a and b the same instance? Judgment
System.out.println(a == b ? "Same instance":"It's a different instance");
//Output: Different instance
Since the two are different instances, changes to int [] b will not affect int [] a.
b[0] = 5;
System.out.println(a[0]);
System.out.println(b[0]);
//output: 1
// : 5
This is a bit confusing when it comes to arranging objects. (For arrays) The clone method returns the reference destination of the new array. This will be the same reference as the source array object.
For example, suppose you have a Dog class
.
class Dog{
private String name;
public Dog(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And I add an array of Dog class
.
Dog[] myDogs = new Dog[4];
myDogs[0] = new Dog("Wolf");
myDogs[1] = new Dog("Pepper");
myDogs[2] = new Dog("Bullet");
myDogs[3] = new Dog("Sadie");
And when you clone dog
...
Dog[] myDogsClone = myDogs.clone();
The two refer to the same element.
System.out.println(myDogs[0] == myDogsClone[0] ? "the same":"Wrong");
System.out.println(myDogs[1] == myDogsClone[1] ? "the same":"Wrong");
System.out.println(myDogs[2] == myDogsClone[2] ? "the same":"Wrong");
System.out.println(myDogs[3] == myDogsClone[3] ? "the same":"Wrong");
//Output: Same(4 times)
What this means is that the two are the same reference, so if you make a change to the cloned array, the change will be reflected in the original array as well.
//Any changes you make to myDogsClone will also be reflected in the values of the elements in myDogs.
myDogsClone[0].setName("Ruff");
System.out.println(myDogs[0].getName());
//Output: Ruff
However, if you create a new instance for the array, the changes will not affect the original instance.
myDogsClone[1] = new Dog("Spot");
System.out.println(myDogsClone[1].getName());
System.out.println(myDogs[1].getName());
//Output: Spot
// Pepper
I learned a lot! : relaxed:
Recommended Posts