Domanda

When overriding an equals property for one of my classes is it possible to implement it as so? The properties in question such as identifier could be String, boolean, Date, Set, or LinkedHashSet

public boolean equals(Object obj)
{
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;

    if (!compareProperty(identifier, other.getIdentifier())) return false;
    //Continue for all properties
}

//Compares any two objects
private boolean compareProperty(Object sourceObject, Object testObject)
{
    if (sourceObject == null)
    {
        if (testObject != null)
            return false;
    }
    else if(!sourceObject.equals(testObject))
    {
        return false;
    }

    return true;
}

Why or why not?

È stato utile?

Soluzione

This is indeed what should be done.

I wouldn't reinvent the wheel, though. Consider using Objects.equals (in Java 7), or Objects.equal (in Guava) or an EqualsBuilder (in apache commons-lang).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top