Why does the equals method of a class in java have to override the default equals method?

does this not have the function of comparison? Doesn"t the compiler automatically ignore the Object in the parameter list according to the degree of matching?

class Circle 
{
    double radius;
    public boolean equals(Circle circle) 
    {
        
        return this.radius==circle.radius;
    }
}
Mar.12,2021

I don't understand the question. If you don't use collections such as hashmap,hashset, there will be no problem with your way of writing. But if your circle object is saved to the collection. If you write it this way, you can't compare it. Because the hashcode method


is not overridden, I simply tested it, and this writing is fine. This equals of yours will be called first. But Object provides an equals method, so why not override it?


it's okay if the equals method is called by other code itself, because the other code calls using the equals (Circle circle) method you're writing now.
but if your class is used as a key such as hashmap, there will be a problem because they will only call the equals (Object obj) method

in Object.

clipboard.png
so generally speaking, it is required to override the default equals method, otherwise it is easy to leave a pit

.
Menu