Reputation: 9
Please solve my doubt about equals(). I think equlas() checks content so in following example it should print true because content is same of both t1 and t2, But it prints false. Why?
public class Test {
public static void main(String args[]) {
Test1 t1 = new Test1(10);
Test1 t2 = new Test1(10);
System.out.println(t1.equals(t2));
}
}
class Test1 {
int a ;
Test1( int x){
a = x ;
}
}
Thanks in advance
Upvotes: 0
Views: 138
Reputation: 129477
equals()
by default compares references; and the references of two different objects (in this case t1
and t2
) are unequal. You have to override it to check for equality between members:
@Override
public boolean equals(Object o) {
return (o instanceof Test1) && a == ((Test1)o).a;
}
As a general rule, it's a good idea to override hashCode()
whenever you override equals()
:
@Override
public int hashCode() {
return a;
}
Upvotes: 2
Reputation: 41935
@Override
public boolean equals(Object obj){
if(!(obj instanceof Test))
return false;
return ((Test)obj).x == this.x;
}
Override equals()
in Test to check value of x
Upvotes: 0
Reputation:
You should override equals()
because default method compares the references.
The method below will compare two objects correctly.
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Test1 other = (Test1) obj;
if (a != other.a)
return false;
return true;
}
Upvotes: 2
Reputation: 68715
You need to override the equals method in your Test1
class. Maybe something like this:
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Test1 other = (Test1) obj;
if (a != other.a)
return false;
return true;
}
Upvotes: 1
Reputation: 178243
You need to override equals
in your Test1
class to get the desired behavior. Otherwise, the class will inherit equals
from Object
, which only determines if the two references refer to the same object. Here, you have different instances, so false
is the result.
Quoting from the linked javadocs:
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
Typically you test if the other object is of the same class, then you compare the individual field(s) for equality.
Upvotes: 2