Reputation: 2043
I am asking very basic question but getting really confused how equals method really works in java. Let take an example I declare three variable of type String at class level something like this.
String a = "abc";
String b = "abc";
String c = new String("abc");
Then write a method to compare them as per java thumb rule.
public void compare(){
System.out.println("a.equals(c) :" + a.equals(c));
System.out.println("a == b :" + (a == b));
System.out.println("a == c :" + (a == c));
}
Now when i run the program it gives me the below out put.
a.equals(c) :true
a == b :true
a == c :false
Now i am confused, as i know String that is written as literal are always created into StringPool. That means variable a and b will be created into StringPool and as per stringPool there will be only one instance and variable a and b will point to this variable. Variable c will be created into heap memory. when i compare a.equals(c) it gives me true how it is possible becuase default implemenation of equals always compare the memory allocation not the content. It should return false.
I was also doing the same thing for integer also like
Integer m = 1;
Integer n = 1;
Integer o = new Integer(1);
public void compareInt(){
System.out.println("m.equals(o) :" + m.equals(o));
System.out.println("m == n :" + (m == n));
System.out.println("m == o :" + (m == o));
}
out is
m.equals(o) :true
m == n :true
m == o :false
Now again confused. All the three variable will be created into head memory because for integer there is now IntegerPool. Then how m == n can give true because again == operator compare the reference not the content, and as per my understanding reference are different. In this case equals method behaving the same as in the String.
can some one help to understand what's going on.
Upvotes: 1
Views: 162
Reputation: 393831
String and Integer override the equals
method, so they don't rely on the default implementation.
For example, here's an implementation of String::equals :
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;
}
Oh, and Integers do have a cache for values between -128 and 127, which explains why m==n
returns true.
Upvotes: 6