2016-12-20 24 views
0

聲納得到下述空指針違規低於線聲納空指針侵犯

existed.keySet()

請你能幫助我們解決這個問題。

private boolean isEqualCaptions(Map<String, String> existed, Map<String, String> updated) { 

     if(existed == null && updated != null) return false; 
     if(existed != null && updated == null) return false; 
     for(String key:existed.keySet()){ 
      if(existed.get(key).compareTo(updated.get(key)) != 0) return false; 
     } 
    return true; 
} 
+1

如果什麼'存在== NULL &&更新= = null'? – shmosel

+1

如果'存在'和'更新'都是空值,那麼你的代碼不可能工作。 –

回答

1

如果existedupdated都是null, 程序將達到循環,existed.keySet()將拋出一個NullPointerException,這就是爲什麼你會得到警告。

在循環之前,您應該添加一個條件以確保existed不是null

private boolean isEqualCaptions(Map<String, String> existed, Map<String, String> updated) { 
    if (existed == null && updated != null) return false; 
    if (existed != null && updated == null) return false; 
    if (existed != null) { 
     for (String key : existed.keySet()) { 
      if (existed.get(key).compareTo(updated.get(key)) != 0) return false; 
     } 
    } 
    return true; 
} 

最後,病情A && !B || !A && B可以使用XOR運算符爲A^B被簡化,所以前兩個if語句可以合併和簡化:

private boolean isEqualCaptions(Map<String, String> existed, Map<String, String> updated) { 
    if (existed == null^updated == null) return false; 
    if (existed != null) { 
     for (String key : existed.keySet()) { 
      if (existed.get(key).compareTo(updated.get(key)) != 0) return false; 
     } 
    } 
    return true; 
} 
+0

...和'updated'以及 –

+0

@ PM77-1在添加了對'exists!= null'的檢查後,我們知道'updated'不能爲'null',因爲如果是的話,函數會早些時候返回。 – janos