Java判斷對象是否爲空的方法:isEmpty,null," "

public static void main(String\[\] args) {  
        String a = new String();  
        String b = "";  
        String c = null;  
        if (a.isEmpty()) {  
            System.out.println("String a is empty");  
        }  
        if (b.isEmpty()) {  
            System.out.println("String b is empty");  
        }  
        if (c == null) {  
            System.out.println("String c = null");  
        }  
        if (null == a) {  
            // 編譯器直接就提示了Dead code,a指向了一個新對象,確定不是null了  
            System.out.println("String a =null");  
        }  
        if (a == "") {  
            System.out.println("a = ''");  
        }  
        if (a.equals("")) {  
            //因爲a是字符串,字符串的比較須要用equals,不能直接用 ==  
            System.out.println("a = ''");  
        }  
        /*if (c.isEmpty()) {  
            // 這裏會報空指針,即null不能使用此方法  
            System.out.println("c == null   and   c.isEmpty");  
        }*/  
          
        List<String> list = new ArrayList<>();  
        //list.add("");  
        if (list.isEmpty()) {  
            System.out.println("list is empty");  
        }  
        System.out.println(list.size());  
    }  
/*Output:  
String a is empty  
String b is empty  
String c = null  
equals:a = ''  
list is empty  
0  
*/
相關文章
相關標籤/搜索