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

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

    To answer your question, firstly I would strongly recommend looking at the Documentation.

    Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

    We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

提交回复
热议问题