gpt4 book ai didi

java - java中的equals方法

转载 作者:搜寻专家 更新时间:2023-11-01 04:05:41 25 4
gpt4 key购买 nike

我读过 java 中的 equals() 方法。我听说它只是根据值(value)进行比较。但是,为什么在下面的值相同但类型不同的情况下返回 false?

public class test {
public static void main(String[] args)
{
String s1="compare";
StringBuffer s2=new StringBuffer("compare");
System.out.println(s1.equals(s2)); //false
}
}

最佳答案

String 实例不能等于 StringBuffer 实例。

查看实现:

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;
}

理论上,你可以有一个 equals 实现,当比较两个不属于同一类的对象时(虽然不在 String 类中),它可能返回 true,但我可以' 考虑这样的实现有意义的情况。

关于java - java中的equals方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com