This time we are talking about the concept of "same" in Java.
--Refering to the same instance --The instances are different, but the values are the same
The former is called "equal" and the latter is called "equivalent".
Object hoge = new Object();
Object huga = hoge; //Copy the hoge reference and assign it to huga
At this time, hoge and huga are said to be the same. The identity is judged by the == operator.
For example
Object hoge = new Object();
Object huga = new Object();
huga = hoge;
Even so, hoge and huga are not the same (because they are different instances).
public class Cat{
private String name;
public Cat(String name) {
this.name = name;
}
}
Create two instances with the same name value using the class.
Cat hoge = new Cat("neko");
Cat huga = new Cat("neko");
As mentioned in the previous section, these two instances are not the same because they have different references. However, each reference has the same value. Such a state is said to be equivalent between hoge and huga.
** Equivalence cannot be judged with ==. ** hoge == huga returns false.
Use the equals method to determine equivalence. ** However, the equals method defined in the Object class is implemented to check the identity. ** **
public boolean equals(Object obj){
return (this == obj);
}
Therefore, whether different instances have the same value (equivalence) is determined by overriding the ** equal method. ** **
public static class Cat {
private String name;
public Cat(String name) {
this.name = name;
}
public boolean equals(Object obj) {
if (obj == null){
return false;
}
if (obj instanceof Cat){
Cat cat = (Cat) obj;
return cat.name == this.name;
}
return false;
}
}
If so, you can judge equivalence by using hoge.equals (huga). By the way, depending on how you write the override of the equal method, you can also judge that in a class with multiple values, if one of the values matches, it is considered to be the same value.
The String type is a reference type data type, but an instance can be created only by a string literal (enclosed in ""). ** Instances created with this string literal are an exception, and the == operator can be used to determine equivalence. ** **
public static void main(String[] args) {
String a= "neko";
String b = "neko";
System.out.println(a == b); //Returns with true
}
This is because string literals are created as constant values in a memory space for constants different from the instance, and there is a mechanism called "constant pool" for reusing references.
However, since this is only when a string literal is used, if a Sring type variable is created with the new operator, the equivalence cannot be determined with the == operator.
Thorough capture Java SE11 Silver problem collection
Recommended Posts