当前位置:网站首页>==What is the difference between and equals?

==What is the difference between and equals?

2022-06-24 00:01:00 The fifth brother of the Wang family

==: Operator , Used to compare base type variables with reference type variables .

For base type variables , Whether the compared variables hold the same values , The type does not have to be the same .

short s1 = 1; long l1 = 1;
//  result :true. Different types , But the value is the same 
System.out.println(s1 == l1);

For reference type variables , The comparison is whether the addresses of the two objects are the same .

Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
//  result :false. adopt new establish , Point to two different objects in memory 
System.out.println(i1 == i2);

equals:Object Methods defined in class , It is usually used to compare whether the values of two objects are equal .

equals stay Object The method is actually equivalent to ==, But in actual use ,equals It is usually overridden to compare whether the values of two objects are the same .

Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
//  result :true. Two different objects , But with the same value 
System.out.println(i1.equals(i2));
 
// Integer Of equals Rewriting methods 
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        //  Are the values saved in the comparison object the same 
        return value == ((Integer)obj).intValue();
    }
    return false;
}

two-object hashCode() identical , be equals() It must be for true, Am I right? ?

incorrect .hashCode() and equals() The relationship is as follows :

When there is a.equals(b) == true when , be a.hashCode() == b.hashCode() It must be true ,

In turn, , When a.hashCode() == b.hashCode() when ,a.equals(b) Not necessarily for true.

原网站

版权声明
本文为[The fifth brother of the Wang family]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206232121148862.html