我有以下代码
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时,为什么我会"假"?
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 的原因。