为什么"=="有时可以使用String.trim?

The*_*ind 5 java string

我有以下代码

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);
}
Run Code Online (Sandbox Code Playgroud)

OP:

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.. 
Run Code Online (Sandbox Code Playgroud)

当我检查s == s3时,为什么我会"假"?

Dee*_*pak 5

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

编辑: 正如Chris Hayes和RJ所建议的那样

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

修剪方法的源代码


Ani*_*kur 2

public String trim() {
    int len = value.length;
    int st = 0;
    char[] val = value;    /* avoid getfield opcode */

    while ((st < len) && (val[st] <= ' ')) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= ' ')) {
        len--;
    }
    return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
Run Code Online (Sandbox Code Playgroud)

System.out.println(s == s2);正如您在 case( )中看到的this那样,返回它指向相同的引用,这就是您得到 true 的原因。