There are two "same" in java.
The == operator determines that they are the same. That is, it is determined that a plurality of variables refer to the same instance.
A a = new A(); //Create an instance called type A
A b = a; //Copy each instance of a to b as it is
System.out.println(a == b);
true
public class Sample {
private int num;
public Sample(int num) {
this.num = num;
}
}
public class Main {
public static void main(String[] args) {
Sample s0 = new Sample(5); //Sample type instantiation
Sample s1 = s0; //Copy to s1
s0 = new Sample(5); //Create a new Sample type instance
System.out.println(s0 == s1);
}
}
false
At the time of copying with Sample s1 = s0;
, it had the same instance, but on the next line, s0
created a new instance, and s0
and s1
became different instances.
The equals method determines that they are equivalent. That is, the instances are different, but it is determined whether they have the same value.
The equals method defined in the default Object class is
public boolean equals(Object obj){
return (this == obj);
}
Because it is defined as, and it is a specification to confirm the identity
*** It is assumed to be used by overriding. *** ***
further! !!
*** When overriding the equals method, you must also override the hashCode in the set. *** ***
equals Keep in mind that in general, when overriding this method, you should always override the hashCode method and follow the general convention of the hashCode method that equivalent objects must hold the equivalent hash code.
public class Sample {
private int num;
private String name;
public Sample(int num, String name) {
this.num = num;
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + num;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Sample other = (Sample) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (num != other.num)
return false;
return true;
}
}
public class Main {
public static void main(String[] args) {
//argument(num, name)Is the same
Sample a = new Sample(5, "xxx");
Sample b = new Sample(5, "xxx");
System.out.println(a.equals(b));
//Output each hashCode
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}
true
3694926
3694926
Overriding the equals and hashCode methods.
If even one num or name is different, it will be as follows.
public class Main {
public static void main(String[] args) {
//argument(name)Is different
Sample a = new Sample(5, "xxx");
Sample b = new Sample(5, "yyy");
System.out.println(a.equals(b));
//Output each hashCode
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}
false
3694926
3725709
The equals judgment is false
, and a different value is output for hashCode.
Recommended Posts