How the equals () method works in Java

The method equalscompares whether or not two values ​​of an object are equal. My question is how does it compare these two objects? How can he say that both objects are equal or not? I want to know based on the fact that it compares two objects. I do not include the method hashCode.

+5
source share
3 answers

The default implementation, one of the class java.lang.Object, simply checks for references to the same object:

150    public boolean equals(Object obj) {
151        return (this == obj);
152    }

The link equality operator is described in the Java Specification :

At run time, the result == is true if the operand values ​​are both null or both refer to the same object or array; otherwise the result is false.

. , Integer ==:

Integer a = new Integer(1000);
Integer b = new Integer(1000);
System.out.println(a==b); // prints false

:

722     public boolean equals(Object obj) {
723         if (obj instanceof Integer) {
724             return value == ((Integer)obj).intValue();
725         }
726         return false;
727     }

:

System.out.println(a.equals(b)); // prints true

, , , ( ).

, hashCode.

+6

:

public class Employee {
    String name;
    String passportNumber;
    String socialSecurityNumber;
    public static void main(String[] args) {
        Employee e1 = new Employee();
        Employee e2 = new Employee();
        boolean isEqual = e1.equals(e2);  // 1
        System.out.println(isEqual);
    }
}

// 1 equals Object, e1 e2. false , new.

Object

public boolean equals(Object obj) {
    return (this == obj);
}

JLS equals . . JLS , programmar . , .
hashcode . hashcode / , . hashcode , , HashMap..

hashcode , , .
, equals true, hashcode .

equals, , , e1 e2 . passportNumber socialSecurityNumber passportNumber+socialSecurityNumber?

I want to know based on what it compares the two objects.

- Object class equals ==. .

+4

, equals ( - ), . "=="

0

All Articles