Overriding the java equals() method - not working?

后端 未结 8 1238
花落未央
花落未央 2020-11-22 02:33

I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a

相关标签:
8条回答
  • 2020-11-22 03:02

    Another fast solution that saves boilerplate code is Lombok EqualsAndHashCode annotation. It is easy, elegant and customizable. And does not depends on the IDE. For example;

    import lombok.EqualsAndHashCode;
    
    @EqualsAndHashCode(of={"errorNumber","messageCode"}) // Will only use this fields to generate equals.
    public class ErrorMessage{
    
        private long        errorNumber;
        private int         numberOfParameters;
        private Level       loggingLevel;
        private String      messageCode;
    

    See the options avaliable to customize which fields to use in the equals. Lombok is avalaible in maven. Just add it with provided scope:

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.14.8</version>
        <scope>provided</scope>
    </dependency>
    
    0 讨论(0)
  • 2020-11-22 03:03

    recordId is property of the object

    @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Nai_record other = (Nai_record) obj;
            if (recordId == null) {
                if (other.recordId != null)
                    return false;
            } else if (!recordId.equals(other.recordId))
                return false;
            return true;
        }
    
    0 讨论(0)
  • 2020-11-22 03:08

    Consider:

    Object obj = new Book();
    obj.equals("hi");
    // Oh noes! What happens now? Can't call it with a String that isn't a Book...
    
    0 讨论(0)
  • 2020-11-22 03:13

    Slightly off-topic to your question, but it's probably worth mentioning anyway:

    Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.

    I also agree that you should use the @Override annotation whenever you're overriding equals (or any other method).

    0 讨论(0)
  • 2020-11-22 03:16

    In Java, the equals() method that is inherited from Object is:

    public boolean equals(Object other);
    

    In other words, the parameter must be of type Object. This is called overriding; your method public boolean equals(Book other) does what is called overloading to the equals() method.

    The ArrayList uses overridden equals() methods to compare contents (e.g. for its contains() and equals() methods), not overloaded ones. In most of your code, calling the one that didn't properly override Object's equals was fine, but not compatible with ArrayList.

    So, not overriding the method correctly can cause problems.

    I override equals the following everytime:

    @Override
    public boolean equals(Object other){
        if (other == null) return false;
        if (other == this) return true;
        if (!(other instanceof MyClass)) return false;
        MyClass otherMyClass = (MyClass)other;
        ...test other properties here...
    }
    

    The use of the @Override annotation can help a ton with silly mistakes.

    Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.

    0 讨论(0)
  • 2020-11-22 03:17

    the instanceOf statement is often used in implementation of equals.

    This is a popular pitfall !

    The problem is that using instanceOf violates the rule of symmetry:

    (object1.equals(object2) == true) if and only if (object2.equals(object1))

    if the first equals is true, and object2 is an instance of a subclass of the class where obj1 belongs to, then the second equals will return false!

    if the regarded class where ob1 belongs to is declared as final, then this problem can not arise, but in general, you should test as follows:

    this.getClass() != otherObject.getClass(); if not, return false, otherwise test the fields to compare for equality!

    0 讨论(0)
提交回复
热议问题