1. 程式人生 > 其它 >什麼情況下不能用 isEmpty

什麼情況下不能用 isEmpty

技術標籤:javajava

結論

等於 null 不能用

實驗一

    public static void abc(String a){
        if (a.isEmpty()) System.out.println("empty");
        if (a == "") System.out.println("==''==");
        if (a == null) System.out.println("null");
    }

    @Test
    public void
test(){ String a = new String(); String b = null; String c = ""; System.out.println("======= a ========"); abc(a); System.out.println("======== b ======="); abc(b); System.out.println("======= c ========="
); abc(c); }

結果執行到 abc(b)時就報錯了
在這裡插入圖片描述

於是

實驗二

    public static void ac(String a){
        if (a.isEmpty()) System.out.println("empty");
        if (a == "") System.out.println("==''==");
        if (a == null) System.out.println("null");
    }

    public
static void b(String a){ if (a == "") System.out.println("==''=="); if (a == null) System.out.println("null"); } @Test public void test(){ String a = new String(); String b = null; String c = ""; System.out.println("======= a ========"); ac(a); System.out.println("======== b ======="); b(b); System.out.println("======= c ========="); ac(c); }

執行結果如下:
在這裡插入圖片描述
顯而易見, 等於 null 不能用

實驗三【再次印證】

	String name = request.getParameter("aaa");
	System.out.println(name);
	if (name.isEmpty()) System.out.println("empty");
	if (name == "") System.out.println("==''==");
	if (name == null) System.out.println("null");

【說明:當引數不存在是,name為null】
當 引數aaa不存在時,同樣報錯java.lang.NullPointerException
當 引數aaa存在時, 無論為空還是不為空,不會報錯!

結論

等於 null 不能用 isEmpty