Reputation: 45
I have read about the equals()
method in java. I've heard that it compares based just on value. But then why is it returning false for my case below where the value is the same but the types are different?
public class test {
public static void main(String[] args)
{
String s1="compare";
StringBuffer s2=new StringBuffer("compare");
System.out.println(s1.equals(s2)); //false
}
}
Upvotes: 3
Views: 167
Reputation: 3996
The equals()
method belongs to Object
.
From the Java docs for Object
Indicates whether some other object is "equal to" this one.
So basically:
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).
If you have a String
and a StringBuffer
they would not be equal to each other.
They might have the same value, but they aren't equal, have a look at the instanceOf()
method.
Upvotes: 0
Reputation: 1350
Yes Eran is right you can't compair two diffrent objects using equals . If you really wants to do that then use toString()
on StringBuffer
System.out.println(s1.equals(s2.toString()));
Upvotes: 0
Reputation: 5629
String
is different from StringBuffer
. Use toString()
to convert it to a String
.
String s1="compare";
StringBuffer s2=new StringBuffer("compare");
System.out.println(s1.equals(s2.toString()));
Upvotes: 3
Reputation: 393771
A String
instance cannot be equal to a StringBuffer
instance.
Look at the implementation :
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) { // this condition will be false in your case
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;
}
In theory you can have an equals
implementation that may return true when comparing two objects not of the same class (not in the String
class though), but I can't think of a situation where such an implementation would make sense.
Upvotes: 11