[英]Sonar null pointer violations
Sonar giving below null pointer violations for below line 声纳在下面的行下面给出了空指针冲突
existed.keySet() 存在.keySet()
Please could you help us to resolve this issue. 请您帮助我们解决此问题。
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;
}
If existed
and updated
are both null
, then the program will reach the loop, and existed.keySet()
will throw a NullPointerException
, that's why you get the warning. 如果
existed
和updated
都null
,那么程序将达到循环, existed.keySet()
将抛出一个NullPointerException
,这就是为什么你会得到警告。
Before the loop, you should add a condition to make sure existed
is not null
. 在循环之前,应添加一个条件以确保不
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;
}
Finally, the condition A && !B || !A && B
最后,条件
A && !B || !A && B
A && !B || !A && B
can be simplified using the XOR operator as A ^ B
, so the first two if
statements can be combined and simplified: A && !B || !A && B
可以使用XOR运算符作为被简化A ^ B
,所以第2 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.