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

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

    Let me give you an example that I find very helpful.

    You can think of reference as the page number of a book. Suppose now you have two pages a and b like below.

    BookPage a = getSecondPage();

    BookPage b = getThirdPage();

    In this case, a == b will give you false. But, why? The reason is that what == is doing is like comparing the page number. So, even if the content on these two pages is exactly the same, you will still get false.

    But what do we do if you we want to compare the content?

    The answer is to write your own equals method and specify what you really want to compare.

提交回复
热议问题