1

私のクラスの1つでequalsプロパティをオーバーライドする場合、そのように実装することは可能ですか?識別子などの問題のプロパティは、String、boolean、Date、Set、または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;
}

なぜまたはなぜそうではないのですか?

4

1 に答える 1

2

これは確かに行われるべきことです。

しかし、私は車輪の再発明はしません。Objects.equals(Java 7の場合)、Objects.equal(Guavaの場合)、またはEqualsBuilderapache commons-langの場合)の使用を検討してください。

于 2012-01-12T07:41:23.030 に答える