判斷一個字符串是否為空方法有三種
str!=null
“”.equal(str)
str.length()!=0
(注意:length是屬性,一般集合類對象擁有的屬性,取得集合的大小。例如:數組.length表示數組的屬性取得數組的長度
length()是方法,一般字符串對象有該方法,也是取得字符串的長度。例如:字符串.length()
在java中有()的表示方法,沒有的表示屬性)
說明:
null表示這個字符串不指向任何的東西,如果這時候調用它的話,會報空指針異常
“”表示它指向一個長度為0的字符串,這個時候調用它是安全的
null不是對象,“”是對象,所以null沒有分配空間,“”分配了空間。例如
String str1=null; str引用為空
String str2=“”; stri引用一個空串
4. 所以,判斷一個字符串是否為空的時候,要先確保他不是null,然后在判斷他的長度。 String str=”xxx”; if(str!=null && str.lengt>0)
以下是代碼測試
public class TestEmpty { public static Long function1(int n, String s) { long startTime = System.nanoTime(); for (int i = 0; i < n; i++) { if (s == null || "".equals(s)) ; } long endTime = System.nanoTime(); return endTime - startTime; } public static Long function2(int n, String s) { long startTime = System.nanoTime(); for (int i = 0; i < n; i++) { if (s == null || s.length() <= 0) ; } long endTime = System.nanoTime(); return endTime - startTime; } public static Long function3(int n, String s) { long startTime = System.nanoTime(); for (int i = 0; i < n; i++) { if (s == null || s.isEmpty()) ; } long endTime = System.nanoTime(); return endTime - startTime; } public static void main(String[] args) { String s = "ss"; for (int i = 0; i < 20; i++) { System.out.PRintln(function1(1000, s)); // 90788 System.out.println(function2(1000, s)); // 22499 System.out.println(function3(1000, s)); // 33947 System.out.println("---------------------------"); } }
當循環次數在100以下的時候function2和 function3的用時差不多,
當達到1000的時候明顯function2的時間較少,建議使用s == null || s.length() <= 0;測試過判斷不為空的方法也是s!=null&&s.length>0的時間較短
本文大部分參考
新聞熱點
疑難解答