I summarized about.
Java has two meanings in the word "same"
--"** Same" that they are the same instance ** --The same value is "** equivalent" **
It's called.
-** Instances are different, but equivalence that they have the same value ** -** Identity that multiple variables refer to the same instance **
It's called.
Each judgment method is as follows.
-** Identity is == operator ** -** equals method ** to see if the referenced instances have the same value **
The code below is like this.
I wrote the detailed processing flow in the comment out, but in the end sample1 and sample2 will be different instances, so the result will be "false".
public class Sample {
private int num;
public Sample(int num) {
this.setNum(num);
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public class Main {
public static void main(String[] args) {
// 1.Create one instance of Sample
Sample sample1 = new Sample(10);
// 2.Prepare another Sample type variable and assign a reference to the first instance
Sample sample2 = sample1; // sample1,sample2 is "same" * Must be the same instance
// 3.In addition, create an instance of Sample and assign a reference to that instance to sample1.
sample1 = new Sample(10);//sample1 and sample2 are not "identical" because they have references to different instances
System.out.println(sample1 == sample2); //Result false
}
}
false
As a measure against Silver ...
-** Instances are different, but having the same value is called equivalence, and it is judged by the equals method. ** ** -** Identity is the property that multiple variables refer to the same instance, and is judged by the == operator. ** **
It's confusing, but remember that if you create a new instance with the same name, it will be a different instance.
-[Thorough capture Java SE 11 Silver problem collection [1Z0-815] correspondence](https://www.amazon.co.jp/%E5%BE%B9%E5%BA%95%E6%94%BB%E7 % 95% A5Java-SE-11-Silver% E5% 95% 8F% E9% A1% 8C% E9% 9B% 86-1Z0-815/dp/4295007625/ref = pd_lpo_14_img_0/356-5238196-1895250? _Encoding = UTF8 & pd_rd_i = 4295007625 & pd_rd_r = 1c21865b-a9fe-43e8-ac01-46170e44abca & pd_rd_w = 9El0Q & pd_rd_wg = hh5Hc & pf_rd_p = 4b55d259-ebf0-4306-905a-7762d1b93740 & pf_rd_r = 72AVCH
Recommended Posts