Correct way to extend a class so I can override equals()
I have a class in a package that I cannot alter. This class does not override Object.equals() and having a different implementation of equals would really make my code cleaner.
I know I can't do this:
MyClass extends OtherClass{
@Override
public boolean equals(MyClass that)
{
//compare members and other stuff here
}
}
OtherClass oc1 = new OtherClass();
Other开发者_如何学GoClass 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
What is the right way to accomplish this?
I could write a method like equals(OtherClass oc1, OtherClass oc2) but this is less useful. If I can implement equals I can make use of things like List.contains or Sets to manage my data and make life easier.
How about creating a wrapper class?
MyWrapper {
private OtherClass data;
MyWrapper(OtherClass data) {
this.data = data;
}
public boolean equals(Object that) {
...
}
}
Add getter for stored object, if necessary.
Do not override equals
and not override hashCode
. Also, embrace Apache Commons lang, it provides many useful classes. Using the Apache Commons EqualsBuilder
and the Apache Commons HashCodeBuilder
classes Your class-that-provides-the-missing-equals-operation will look something like this:
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();
}
}
I googled and found this: example
精彩评论