Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding HashMap equals method in Java

I noticed in the source code for HashMap it lists the equals method as final. Why is it that when I override it I do not get a compile error?

public class Test extends HashMap<Object, Object> {

    @Override
    public boolean equals(Object o) {
        return false;
    }
}

Java HashMap equals method:

public final boolean equals(Object o) {
    if (!(o instanceof Map.Entry))
        return false;
    Map.Entry e = (Map.Entry)o;
    Object k1 = getKey();
    Object k2 = e.getKey();
    if (k1 == k2 || (k1 != null && k1.equals(k2))) {
        Object v1 = getValue();
        Object v2 = e.getValue();
        if (v1 == v2 || (v1 != null && v1.equals(v2)))
            return true;
    }
    return false;
}
like image 779
deelo55 Avatar asked Sep 11 '26 10:09

deelo55


1 Answers

That's the equals method for HashMap.Entry, not HashMap itself - look at how it's trying to use the reference passed into it as a Map.Entry.

like image 102
Jon Skeet Avatar answered Sep 13 '26 00:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!