mardi 10 mai 2016

Why is Class type field not returning true after overriding equals and hashCode

I build a class called Identity that holds a Class field and a String field to identify what class I should use Reflection on and the String parameter that its constructor receives.

Then I came across having to override hashCode and equals to find if the objects where equal when they contained the same Class and String fields, but I kept getting false.

I figured out that the problem was inside the Class field but I don't know the reason why its hashCode is different when the object where I used the getClass method was from the same object throughout the debugging process.

Why is the hashCode different between the two calls of the getClass method?

Functional hashCode and equals would also help.

public class Identity
{

private Class clazz;

private String name;

public Identity(Class clazz, String name)
{
    this.clazz = clazz;
    this.name = name;
}

public void setClazz(Class clazz)
{
    this.clazz = clazz;
}

public Class getClazz()
{
    return clazz;
}

public void setName(String name)
{
    this.name = name;
}

public String getName()
{
    return name;
}

@Override
public int hashCode()
{
    int hash = 3;
    hash = 29 * hash + Objects.hashCode(this.clazz);
    hash = 29 * hash + Objects.hashCode(this.name);
    return hash;
}

@Override
public boolean equals(Object obj)
{
    if(this == obj)
    {
        return true;
    }
    if(obj == null)
    {
        return false;
    }
    if(getClass() != obj.getClass())
    {
        return false;
    }
    final Identity other = (Identity) obj;
    if(!Objects.equals(this.name, other.getName()))
    {
        return false;
    }
    return Objects.equals(this.clazz, other.getClass());
}

}





Aucun commentaire:

Enregistrer un commentaire