I constructed a class with one String
field. Then I created two objects and I have to compare them using ==
operator and .equals()
too. Here's what I've done:
public class MyClass {
String a;
public MyClass(String ab) {
a = ab;
}
public boolean equals(Object object2) {
if(a == object2) {
return true;
}
else return false;
}
public boolean equals2(Object object2) {
if(a.equals(object2)) {
return true;
}
else return false;
}
public static void main(String[] args) {
MyClass object1 = new MyClass("test");
MyClass object2 = new MyClass("test");
object1.equals(object2);
System.out.println(object1.equals(object2));
object1.equals2(object2);
System.out.println(object1.equals2(object2));
}
}
After compile it shows two times false as a result. Why is it false if the two objects have the same fields - "test"?
Your implementation must like:
With this implementation your both methods would work.
==
compares object references, it checks to see if the two operands point to the same object (not equivalent objects, the same object).If you want to compare strings (to see if they contain the same characters), you need to compare the strings using
equals
.In your case, if two instances of
MyClass
really are considered equal if the strings match, then:...but usually if you are defining a class, there's more to equivalency than the equivalency of a single field (
a
in this case).Side note: If you override
equals
, you almost always need to overridehashCode
. As it says in theequals
JavaDoc:The "==" operator returns true only if the two references pointing to the same object in memory. The equals() method on the other hand returns true based on the contents of the object.
Example:
Output: Comparing two strings with == operator: false Comparing two Strings with same content using equals method: true Comparing two references pointing to same String with == operator: true
You can also get more details from the link: http://javarevisited.blogspot.in/2012/12/difference-between-equals-method-and-equality-operator-java.html?m=1
IN the below code you are calling the overriden method .equals().
public boolean equals2(Object object2) { if(a.equals(object2)) { // here you are calling the overriden method, that is why you getting false 2 times. return true; } else return false; }