正如我所读到的 equals()
方法用于比较 java 中的字符串是否相等,但是当我运行此代码时,我得到输出 false 。为什么?
public class TestStringBuilder {
public static void main(String[] str){
StringBuilder sb1= new StringBuilder("Hello World");
StringBuilder sb2= new StringBuilder("Hello World");
System.out.println(sb1.equals(sb2));
}
}
最佳答案
在字符串构建器中,由于没有覆盖 .equals()
方法,因此调用对象 .equals()
方法
这相当于对象引用而不是其值。
在 String 类中,这已被重写以比较每个位置的值,然后返回结果
这是 String 类中重写的 .equals()
方法,它可以 self 解释为什么会发生这种情况
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count; //count is the length of return in the docs
if (n == anotherString.count) {
char v1[] = value;//The value is used for character storage.
char v2[] = anotherString.value;
int i = offset; //The offset is the first index of the storage that is used.
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
关于java - 在比较两个具有相同值的 stringbuilder 对象时,StringBuilder 给我错误的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29788777/