I have two objects of type MyObject. Their private fields have things like Integer, int, Long, long, String
, etc -- no fancy sub-objects or anything to this effect.
I want to check to see if their fields are equal. I am not trying to check if they are the same object in memory (the same reference?), which they shouldn't be anyway since these two objects are from separate lists / created separately.
What is the correct way to check if all the fields of one object have the same values as all the other fields of the second object?
5 Answers 5
The best way is to override the method equals(Object)
and let your IDE
implements it for you.
8 Comments
public boolean equals(Object obj)
, checked if obj
was an instance of myObject
, typecasted it, and then returned a big and-chain of field comparisons. Is this all I have to do?You need to override the equal method in your class and compare if the values of the two class are same return true else false. example:
obj1.equals(obj2);
in your class
@Override
public boolean equals(YourClass obj) {
// compare the values of both objets.
// return true on success;
}
Comments
Use Object.equals() to compare
Comments
Overriding Object
's equals
method is the best choice for your situation. You can either ensure the equality of every field of the object, or you can just compare a field or combination of fields that you know will be unique.
If you're using collections such as Map
s, you might consider overriding hashcode
using these fields instead, and then compare hashcodes in the equals
method.
For your reference:
equals
should always determine if two objects are "equal" in concept (which usually means they have the same fields).==
compares memory location, and thus equality between primitive typesComparable
interface is used to order an object "ahead" or "behind" another object; useful for sorting arrays and collections.Comparator
interface is similar toComparable
but uses a "third-party" object to compare two other objects. ThisComparator
can be passed into collection-sorting methods if you don't want your objects to beComparable
.
Comments
mDo as @Raj K suggested. For example, if you have:
public class MyObject {
int i1;
long l1;
long i2;
// and a bunch of c'tors and methods
}
then your equals() method would be something like
public Boolean equals( Object o ) {
if ( o instanceof MyObject ) {
MyObject m = (MyObject)o;
return (i1==m.i1) && (l1==m.l1) && (l2==m.l2);
}
return false;
}
If any of your fields are Objects, you have to be a bit more careful, since you also have to first check for null's before checking whether
this.something.equals(m.something)
.equals
?boolean equals(Object o)
method..equals
is the correct thing to do here, as opposed to doingobject1 == object2
orobject1.equals(object2)
or implementingComparable
orComparator
or something. Too many options and I am unsure which is correct.