Why do we have to override the equals() method in Java?

后端 未结 8 1949
臣服心动
臣服心动 2020-11-28 09:47

I have some confusion about the reason that we override the .equals method.

For example:

Test test1 = new Test(3);
Test test2 = new Test         


        
相关标签:
8条回答
  • 2020-11-28 10:15

    .equals() doesn't perform an intelligent comparison for most classes unless the class overrides it. If it's not defined for a (user) class, it behaves the same as ==.

    Reference: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html http://www.leepoint.net/data/expressions/22compareobjects.html

    0 讨论(0)
  • 2020-11-28 10:17

    Object.equals() method checks only reference of object not primitive data type or Object value (Wrapper class object of primitive data, simple primitive data type (byte, short, int, long etc.)). So that we must override equals() method when we compare object based on primitive data type.

    0 讨论(0)
提交回复
热议问题