Is there any library, given two objects of any java class would precisely say whether they are equal or not? (the class may not have hashCode defined)
else is there any simple way to implement this?
Is there any library, given two objects of any java class would precisely say whether they are equal or not? (the class may not have hashCode defined)
else is there any simple way to implement this?
I was looking for something similar to this
http://code.google.com/p/deep-equals/
This will check for semantic equality between objects using value equivalence if the hash codes and equals aren't defined.
IMHO , There are no libraries to check that two Objects are equal(Since that equal should define by you).
You need to override equals
method and implement your logic inside.
@Override
public boolean equals(Object other){
//your logic
}
the class may not have hashCode defined
Beware of that statement, when you use/deal with Collections you'll end up with surprise results ,since you are not overriding hashcode
method.
Be careful with equals and override contract
Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
You need to override equals()
and hashCode()
method of your custom class.
Default implementation of equals()
internally just does == comparison. It means it will just check if both the references you are comparing are pointing to same object or not. If you want to also compare actual data in it you have no option than to override it to add your comparison logic.
You could use Apache Commons' EqualsBuilder
which provides a reflectionEquals(a,b)
method.
But in most cases it would still be best to implement equals
and hashCode
yourself (note that by contract you should always override both).
Note that most collections depend on equals
and hashCode
to be correctly implemented but if you have a common super class, you might be able to override then there like this:
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
NOTE: please be aware that reflection adds some performance overhead so heavy use of those methods might not be wise.
You can use EqualsBuilder from commons-lang. http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/builder/EqualsBuilder.html#reflectionEquals%28java.lang.Object,%20java.lang.Object%29
The reflectionEquals method will check every field in the object against an other object for equality. It's working with reflection. If you don't implement equals() then it simply checks the references. Implementing equals() and hashCode() is still advisable.