1、檢查String是否相等
如上文提到的,檢查String是否相等最好要使用equals方法,儘量少使用==操作符。
String cmower ="cmower";
System.out.println("cmower" == cmower);//true
System.out.println("cmower".equals(cmower));//true
System.out.println("cmower".substring(0, 3) == "cmo");//false
System.out.println("cmower".substring(0, 3).equals("cmo"));//true
String cmower ="cmower"; System.out.println("cmower" == cmower);//true System.out.println("cmower".equals(cmower));//true System.out.println("cmower".substring(0, 3) == "cmo");//false System.out.println("cmower".substring(0, 3).equals("cmo"));//true
1- 2
- 3
- 4
- 5
- 6
- 1
- 2
- 3
- 4
- 5
- 6
- ==操作符確定的是兩個String是否放在同一個位置上。
- “cmower”字符串和cmower變量指向的引用就是在同一個位置上,所以==比較結果爲true。
- 在Java虛擬機上,只有字符串常量是共享的(”cmower”字符串和cmower變量共享了同一個地址)。但是對於substring產生的結果就不共享了。
- 對於equals,比較的則是兩個對象是否具有相同的字符集。
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
2、String不可變
public static void main(String[] args) { String s = "s"; String ss = toUpper(s); System.out.println(s);//s System.out.println(ss);//S } private static String toUpper(String b) { String bb = b.toUpperCase(); System.out.println(b);//s return bb; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
“s”是一個字符串對象,你怎麼也不能把這個對象變成“S”。也就是說小s和大S儘管是雙胞胎,但她們倆註定都不能成爲對方。
3、+與StringBuilder
首先,我們先來看對於+操作符,在Java虛擬機下是如何工作的。
public static String add1() { String b = "b"; String s = "a" + b + "c" + "d" + 100; return s; } public static String add2() { String s = "a" + "b" + "c" + "d" + 100; return s; }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
對於add1和add2方法,你認爲Java虛擬機的工作方式一樣嗎?
閉上眼睛10秒鐘,先想一會。
我們來揭曉答案:
差別是不是很大?
這說明,+操作符在拼接String時,會根據情況做一定的選擇。比如add1方法,Java會new 一個StringBuilder對象,來對abcd100進行append操作,之後再toString出來。
那麼也就說,Java會自動會爲我們優化代碼,以後我們儘管使用+操作符就行了。但事實並非如此,再來看一串代碼。
public static String plus() { String result = ""; for (int i = 0; i < 10; i++) { result += "a"; } return result; } public static String sb() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { sb.append("a"); } return sb.toString(); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
這個時候,你選擇用sb方法還是plus方法?
再閉上眼睛10秒鐘,想一下你的答案。
javap執行結果如下:
看得出plus方法的8-34行是一個循環,11行時創建了StringBuilder對象,也就是在循環內。這個方法執行了10次,那麼也就創建了10個StringBuilder對象。
再來看sb方法的結果:
顯而易見,StringBuilder對象只有一個。在使用StringBuilder時,儘量少“在append方法的參數中使用+操作符”:
public static String sb1() { StringBuilder sb = new StringBuilder(); String b = "b"; for (int i = 0; i < 10; i++) { sb.append("a" + b); } return sb.toString(); }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
這樣做糟糕至極:
“a” + b時又重新創建了StringBuilder對象。
總結如下,
1. 在進行循環多次拼接String時,用StringBuilder而不用+操作符!
2. +操作符只用於少量字符串變量拼接,在內存中操作,性能更高!
3. append方法的參數少用+操作符!