2015-03-30 67 views
-2

我在打印選定的地圖值時遇到的問題是NullPointerException。如果selectedCert列表包含(AABBCC),地圖上會打印:如何在地圖中處理空值

EN
EN
EN

但是,如果selectedCert列表只包含2個是(AA,BB),會出現空指針異常,因爲ccLang爲空。

剪斷代碼:

private String ccLang;//Setter and Getter  
    Map<String, String> Cert = new HashMap<String,String>(ss.size()); 

    Cert.put("AA", "EN");  
    Cert.put("BB", "EN");  
    Cert.put("CC", ccLang); 

    for(String key: selectedCert)  
     System.out.println(Cert.get(key));  
    System.out.println(); 

如何解決這個問題?

+0

在調用「put」之前做空檢查,是你在找什麼R' – kosa 2015-03-30 19:30:35

+0

'NullPointerException'來自哪裏?一個'HashMap'允許有'null'鍵和值。 – 2015-03-30 19:35:02

+0

你可以請驗證你的代碼?你發佈的那個不會被編譯,如果「固定」你不會得到一個NPE,它只會打印null ... – migueldiab 2015-03-30 19:35:43

回答

0

如果你的值可以爲null,只需添加一個空檢查:

if(value != null) { 
    map.put(key, value); 
} 

可以使用的方法爲它:

private static void putNonNull(String key, String value, 
           Map<String, String> map) { 
    if(value != null) { 
     map.put(key, value); 
    } 
} 

putNonNull("AA", "EN", Cert); 
putNonNull("BB", "EN", Cert); 
putNonNull("CC", ccLang, Cert); 
+0

謝謝,我試過你的方式,但它仍然顯示空指針異常。 ccLang變量的初始值是「」(兩行情=空白) – Learner30 2015-03-30 19:47:04

0

我編輯的代碼位,看看這個是你在說什麼,但這會很好:

String ccLang = null;//Setter and Getter 

    Map<String, String> Cert = new HashMap<String,String>(10); 

    Cert.put("AA", "EN"); 

    Cert.put("BB", "EN"); 

    Cert.put("CC", ccLang); 

    for (Entry<String, String> entry : Cert.entrySet()) { 
     System.out.println(entry.getKey()); 
     System.out.println(entry.getValue()); 
    } 
+0

感謝您的幫助 – Learner30 2015-03-30 19:53:40