问题
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
}
}
回答1:
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.
回答2:
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()));
回答3:
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()));
回答4:
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.
来源:https://stackoverflow.com/questions/31805123/equals-method-in-java