Sobes.tech
Junior

Mida teeb meetod equals()?

sobes.tech AI

Vastus AI-lt

The equals() method in Java compares two objects to determine if they are equal.

By default (in the Object class), it checks if the references to the objects are the same (if they point to the same instance in memory).

Classes can override this method to define logical equality of objects based on their content (for example, two String objects are considered equal if they contain the same sequence of characters, even if they are different instances).

When overriding equals(), it is also necessary to override the hashCode() method to adhere to the following contract: if two objects are equal according to equals(), then their hashCode() methods must return the same value.

Example of overriding:

class MyClass {
    private int value;

    public MyClass(int value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true; // Reference comparison
        if (o == null || getClass() != o.getClass()) return false; // Null and type check
        MyClass myClass = (MyClass) o; // Type casting
        return value == myClass.value; // Logical comparison based on value
    }

    @Override
    public int hashCode() {
        return Objects.hash(value); // Hash code generation
    }
}