gpt4 book ai didi

java - 为什么 "=="有时会与 String.trim 一起使用?

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:32 26 4
gpt4 key购买 nike

我有以下代码

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

String s = "abc";
System.out.println(s.hashCode());
String s1 = " abc ";
System.out.println(s1.hashCode());
String s2 = s.trim();
System.out.println(s2.hashCode());
String s3 = s1.trim();
System.out.println(s3.hashCode());
System.out.println();
System.out.println(s == s1);
System.out.println(s == s2);
System.out.println(s == s3);
}

运算符(operator):

96354
32539678
96354
96354

false -- Correct
true -- This means s and s2 are references to the same String object "abc" .
false -- s3=s1.trim()... which means s3="abc" yet s==s3 fails.. If the above conditon were to be considered (s==s2 is true..) , this should also be true..

为什么我在检查 s==s3 时得到“false”?...

最佳答案

因为 s1.trim() 将返回一个新实例。字符串是不可变的,所以每次在字符串上应用一个函数时,都会返回一个新实例,并且您正在使用 == 来比较实例相等性

编辑: 根据 Chris Hayes 和 R.J. 的建议

trim 很聪明,如果没有要修剪的空白,则返回 this。所以在第二种情况下你有' abc '空格所以在这种情况下它不返回 this 而是一个新的字符串实例。

trim method的源代码

关于java - 为什么 "=="有时会与 String.trim 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20650452/

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