Overriding the java equals() method - not working?

后端 未结 8 1237
花落未央
花落未央 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: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.

提交回复
热议问题