正确的扩展类的方法,所以我可以覆盖equals()

时间:2010-12-17 20:22:19

标签: java inheritance

我有一个课程,我无法改变。这个类不会覆盖Object.equals(),并且具有不同的equals实现会使我的代码更清晰。

我知道我不能这样做:

MyClass extends OtherClass{
@Override
public boolean equals(MyClass that)
{
//compare members and other stuff here
}
}

OtherClass oc1 = new OtherClass();
OtherClass oc2 = new OtherClass();
oc1.equals(oc2); //false because of Object.equals
//I want to do something like the following
MyClass mc1 = (MyClass) oc1; //throws class cast exception
MyClass mc2 = (MyClass) oc2; //throws class cast exception
mc1.equals(mc2); //true

实现这一目标的正确方法是什么?

我可以编写一个像equals(OtherClass oc1,OtherClass oc2)这样的方法,但这没用。如果我可以实现equals,我可以使用List.contains或Sets之类的东西来管理我的数据并让生活更轻松。

3 个答案:

答案 0 :(得分:4)

如何创建包装类?

MyWrapper {
    private OtherClass data;

    MyWrapper(OtherClass data) {
        this.data = data;
    }

    public boolean equals(Object that) {
        ...
    }
}

如有必要,为存储对象添加getter。

答案 1 :(得分:1)

不要覆盖equals而不是覆盖hashCode。另外,拥抱Apache Commons lang,它提供了许多有用的类。使用Apache Commons EqualsBuilder和Apache Commons HashCodeBuilder 类您提供的缺少等于操作的类看起来像这样:

public class NiceBerry extends NaughtyBerry
{
    public boolean equals(Object rhsObject)
    {
        if (rhsObject == null)
        {
            return false;
        }

        if (rhsObject == this)
        {
            return true;
        }

        if (rhsObject instanceof NiceBerry)
        {
            EqualsBuilder equalsBuilder = new EqualsBuilder();
            NiceBerry rhs = (NiceBerry)rhsObject;

            equalsBuilder.append(getField1(), rhs.getField1());
            equalsBuilder.append(getField2(), rhs.getField2());
            ... append all the naughty berry fields

            return equalsBuilder.isEquals();
        }
        else
        {
            return false;
        }
    }

    public int hashCode()
    {
        // you pick a hard-coded, randomly chosen, non-zero, odd number
        // ideally different for each class
        HashCodeBuilder hashBuilder = new HashCodeBuilder(17, 37);

        hashBuilder.append(getField1());
        hashBuilder.append(getField2());
        ... append all the naughty berry fields

        return hashBuilder.toHashCode();
    }
}

答案 2 :(得分:-1)

我用Google搜索并发现:example