java String 的比較


先看一段代碼:

 1 public class StringCom {  2 
 3     public static void main(String[] args) {  4         String a = "hello";  5         String b = "hello";  6         String c = new String("hello");  7         char d[] = {'h','e','l','l','o'};  8         
 9         System.out.println(a==b);  //true
10 
11         System.out.println(a==c);  //false
12  
13         System.out.println(a==d);  // Incompatible operand types String and char[]
14 
15         System.out.println(a.equals(d)); //false , 提示:Unlikely argument type for equals(): char[] seems to be unrelated to String
16         
17         System.out.println(a.equals(new String("hello")));  //true
18 
19  } 20 
21 }

遇到一個問題,就像上面的5個比較,問哪個會輸出false,至於第13行的那個,在Eclipse里直接報錯 “Incompatible operand types String and char[]  ”  , 所以意思是,也不會輸出false?還沒運行就報錯了。

 

還有就是看到一個討論:https://www.nowcoder.com/questionTerminal/e426ba1e900c4a7ea000e9a029653aae?from=relative 

里面有關於 ‘==’和‘equals’的討論,有些回復看得我懵逼了,推薦一篇博客:https://www.cnblogs.com/zhxhdean/archive/2011/03/25/1995431.html

還有知乎的一個回答:https://www.zhihu.com/question/26872848

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM