Java – have I implemented equals and hashcode correctly using Google guava?

I am using hibernate and need to rewrite equals and hashcode () I chose to use Google guava's equals and hashcode assistants

I wonder if I missed something here

I have get / set methods for idimage and filepath

@Entity
@Table(name = "IMAGE")
public class ImageEntity {
    private Integer idImage;
    private String filePath;

    @Override
    public int hashCode() {
        return Objects.hashCode(getFilePath());
    }

    @Override
    public boolean equals(final Object obj) {
        if(obj == this) return true;
        if(obj == null) return false;

        if(obj instanceof ImageEntity){
            final ImageEntity otherImage = (ImageEntity) obj;
            return Objects.equal(getFilePath(),otherImage.getFilePath());
        }
        return false;
    }
}

Edit:

Inherit and own the sample here

Solution

The problem with the instanceof operator is that it can take into account polymorphism, if I can say so

For example, you do this:

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

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, a call equal to call will return true because of the instanceof operator

I know it sounds like a basic thing, most people know, but it's easy to forget it Now, if you want such behavior, well, what you achieve is right However, if you think that the imageentity object cannot be equal to (assuming) the advancedimageentity object, declare the imageentity as final or forget instanceof and implement the equals method:

@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 real type of the object, regardless of the type of reference If the obj parameter is an instance of a subclass, it will "slide" through instanceof But getClass is more strict and will not be allowed

PS: I'm not saying instanceof is bad and should not be used I'm just saying you have to be aware of this special situation and decide whether to take it into account

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>