Home > Software engineering >  How do equals and hashCode work under the hood?
How do equals and hashCode work under the hood?

Time:07-07

I researched this question and the answers I got do not satisfy me as they don't explain these things deeply enough. So, it is known that for HashSet with a parametrized custom class it is necessary to override hashCode and equals in order to forbid duplicates. But in practice when I tried to understand how this really works I didn't quite get it. I have a class:

static class Ball {
    String color;

    public Ball(String color) {
        this.color = color;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Ball ball = (Ball) o;
        return Objects.equals(color, ball.color);
    }

    @Override
    public int hashCode() {
        return Objects.hash(color);
    }
    }

In equals method, it is all clear. If two 'variables' are pointing to the same object in memory, then they are equal; if an o is null or they are not of the same class - they are not equal. The last line of equals is what's concerning me. When I go to the Objects.equals :

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

It says once again if two 'variables' refer the same object, then they are equal or if the first object is not null and it is equal to the second one. This equals is Object.equals which will return true if only these two objects aka 'variables' are pointing to the same object in memory. So, how does this really works? Been looking for a clear answer, but as I said, what I've got so far does not satisfy me at all.

CodePudding user response:

In your class, you explained it very well.

The part that you are missing is that at some point, your code will delegate to the equals and hashCode on the color attribute, which is implemented by the java.lang.String class.

See e.g. https://github.com/openjdk-mirror/jdk7u-jdk/blob/f4d80957e89a19a29bb9f9807d2a28351ed7f7df/src/share/classes/java/lang/String.java#L1013 and https://github.com/openjdk-mirror/jdk7u-jdk/blob/f4d80957e89a19a29bb9f9807d2a28351ed7f7df/src/share/classes/java/lang/String.java#L1494

  •  Tags:  
  • java
  • Related