gpt4 book ai didi

Java .equals 介于 String 和 StringBuilder 之间

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

class returntest
{



public static void main(String...args)
{

String name1 = "Test";
String s = new String("Test");
StringBuilder sb = new StringBuilder("Test");

System.out.println(name1.equals(sb)); //Line 1
System.out.println(name1.equals(s)); //Line 2
System.out.println(s.equals(sb)); // Line 3
System.out.println(s.equals(name1)); //Line 4
}

}

下面是输出

false
true
false
true

第 1 行返回,第 3 行返回 false。

我不明白为什么编译器不认为“name1”和“sb”包含相同的值

同样,编译器不认为“s”和“sb”包含相同的字符串(两者都是非原始字符串)。

有人可以解释第 1 行和第 3 行的输出吗?

最佳答案

因为它们都是不同的对象

String object!= StringBuilder object.

但是,你的疑问是

name1.equals(s)  returning true

因为在 String 类中 equals 方法是以这种方式验证的。

为了获得所需的输出,请将您的 StringBuilder 转换为 String

System.out.println(s.equals(sb.toString())); //return true.

如果您看到 Source code of String#equals()

1012    public boolean  equals(Object anObject) {
1013 if (this == anObject) {
1014 return true;
1015 }
1016 if (anObject instanceof String) { //key line
1017 String anotherString = (String)anObject;
1018 int n = count;
1019 if (n == anotherString.count) {
1020 char v1[] = value;
1021 char v2[] = anotherString.value;
1022 int i = offset;
1023 int j = anotherString.offset;
1024 while (n-- != 0) {
1025 if (v1[i++] != v2[j++])
1026 return false;
1027 }
1028 return true;
1029 }
1030 }
1031 return false;
1032 }

if (anObject instanceof String) { 如果您传递 StringBuilder,则总是返回 false。

关于Java .equals 介于 String 和 StringBuilder 之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18544830/

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