简体   繁体   中英

Java Comparing two properties by object references

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM