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

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

    By default .equals() uses == identity function to compare which obviously doesn't work as the instances test1 and test2 are not the same. == only works with primitive data types like int or string. So you need to override it to make it work by comparing all the member variables of the Test class

提交回复
热议问题