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

后端 未结 8 2015
臣服心动
臣服心动 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:57

    From the article Override equals and hashCode in Java:

    Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.

    Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:

    many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same

    Integer wrapper class overrides equals to perform numerical comparison etc.

提交回复
热议问题