Did I implement equals and hashCode correctly using Google Guava?

前端 未结 3 2137
长发绾君心
长发绾君心 2021-02-20 17:18

I am using hibernate and need to override equals and hashCode(). I chose to use google-guava\'s equals and hashCode helpers.

I wanted to know if I am missing something

3条回答
  •  野的像风
    2021-02-20 17:42

    The problem with the instanceof operator is that it works taking into account polymorphism, if I may say so.

    Let's say, for example, that you do this:

    public class AdvancedImageEntity extends ImageEntity
    {
        //some code here
    }
    

    and then you do this:

    ImageEntity ie = new ImageEntity ();
    AdvancedImageEntity advanced_ie = new AdvancedImageEntity ();
    
    boolean this_will_be_true = ie.equals (advanced_ie);
    

    As the name suggests, that equals call will return true, because of the instanceof operator.

    I know this sounds like basic stuff and most people know it, but it's SOOOO damn easy to forget it. Now, if you want that behaviour, then it's fine, you implemented equals correctly. But if you consider that an ImageEntity object must not be equal to an (hypothetical) AdvancedImageEntity object, then either declare ImageEntity to be final OR forget about instanceof and implement your equals method like this:

    @Override public boolean equals(final Object obj)
    {
        if(obj == this) return true;
        if(obj == null) return false;
    
        if (getClass ().equals (obj.getClass ()))
        {
            final ImageEntity otherImage = (ImageEntity) obj;
    
            return Object.equals (getFilePath(), otherImage.getFilePath());
        }
    
        return false;
    }
    

    This will check the object's true type, no matter what type the reference is. If the obj parameter is an instance of a subclass, it would "slip" by instanceof. But getClass is a lot more strict and won't allow it.

    PS: I'm not saying that instanceof is bad and should not be used. I'm just saying that you must be aware of this particular situation and decide whether to use it taking this into account.

提交回复
热议问题