声纳空指针违规
声纳低于行下面的空指针违规
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; }
如果existed
和updated
都是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
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; }