This is my code:
Object a = "1234";
Object b = new Integer("1234");
I know that ==
means references and equals()
means contains.
Now why a.equals(b)
is false?
Each of them has the same value.
This is my code:
Object a = "1234";
Object b = new Integer("1234");
I know that ==
means references and equals()
means contains.
Now why a.equals(b)
is false?
Each of them has the same value.
Because both are from different classes. a
is from String
class, and b
is from Integer
class. So, it will return false
without going further and checking the content of the instances.
Even though, you have declared both instances with Object
reference, but, in the run time, when you call .equals()
method, they will delegated to their actual classes of the instances.
For example if you take String
class equals()
method, it will be like
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
So, if you passed an instance of another class, it will return false
.
Your a
is an Object
container, containing a String
object, while your b
is an Object
container, containing an Integer
object.
When you call equals()
on a
, it does String.equals()
, which finds out that your String
just isn't equal to an Integer
and no amount of auto-boxing and -unboxing can make it so.
As Kugathasan Abimaran already gave an explanation I will just add this small code with which you can see for yourself:
System.out.println(a + " might look like " + b + " but " + a.getClass() + " does not equal " + b.getClass());
Which will result in:
1234 might look like 1234 but class java.lang.String does not equal class java.lang.Integer