Overriding rules for equal's method in Java

Asked 2 years ago, Updated 2 years ago, 121 views

I'm studying Java with googling, and I saw a post saying that it's better to use the same as you inherited instead of overriding the equals. But if you want to override the equals, I told you to only do it when you meet certain rules. I saw the article before and tried to make it while practicing, but I can't remember it well. I wanted to browse the page again, but I forgot how I searched it, so I couldn't find it. Since it is a universal rule, most Java developers must be familiar with it, do you know?

java equals override

2022-09-22 12:36

1 Answers

I've seen something similar in a book called Effective Java. If you are satisfied with any of the following, it is recommended that you use the same as you inherited the equals. If you're not satisfied at all, you can override it.

If you look at Item 8 in Chapter 3 of Effective Java, it says, "When you override the equals method, follow a universal contract." Here's the story.

@Override
public boolean equals(Object o){
    THROW NEW ASSERTIONError();//method is never invoked.
}

Rather than judging whether an instance is identical by object reference alone, it is a class that requires comparing the values of the instance to determine if it is logically identical, and is good when you do not override the equals method in your superclass.

For example, for classes that represent values such as Integer or Date, you need to override the equals method.


2022-09-22 12:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.