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

后端 未结 8 1943
臣服心动
臣服心动 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 09:51

    The default behavior for java.lang.Object is to compare references, but that's not appropriate for every kind of object. There are things called Value Objects (like BigDecimal or String), where objects with the same value are considered to be interchangeable, so the default behavior of equals is not desirable. Those kinds of objects have to implement equals and hashcode based on the value that the object takes on.

提交回复
热议问题