這個地方最容易出的問題就是 == equals 的問題
== 與 equals方法 的區別
== 比較的是地址值
equals比較的也是地址值(更確切的說是hashCode),但是String裡邊重寫了這個方法,比較的是具體內容的值
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = char v2[] = anotherString. int i = offset;
int j = anotherString.offset;
while (n-- != 0) { //直接比較的是每個字符
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
字符串拼接 學這塊內容 大家務必搞清楚每一步 這些變量 常量 對象 在內存上的變化
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2); //false,s1+s2是一個新的String的地址的引用
s3.equals((s1 + s2));
System.out.println(s3 == "hello" + "world");//true,拼接起來的是常量池中找到的
s3.equals("hello" + "world");
現在大家只要知道 凡是有變量參加的字符串拼接 拼出來的東西 一定是 new 出來的對象 若都是字符串常量的拼接 則還是直接去常量池找的常量 //這個東西我留著專門寫個東西介紹什麼叫做 編譯期確定下來了 假如你這麼寫:
String a = "ab"; final String bb = "b"; /編譯時已經放入常量池 String b = "a" + bb; System.out.println((a == b)); //result = true
方法返回
String a = "ab";
final String bb = getBB();
String b = "a" + bb;
System.out.println((a == b)); //result = false
private static String getBB() { return "b"; }
這兩個東西我放到編譯期確定下來了這篇文章給大家分析一下 2016-10-21 更新