Java 字符串字面量表达式应位于等于比较的左侧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24656018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String literal expressions should be on the left side of an equals comparison
提问by Wolverine789
!mapData.get("PARTY_ID").equals("") // <-- gives SonarQube error
In the above piece of code, I am getting "String literal expressions should be on the left side of an equals comparison" this error in Sonar. So how we can avoid it.
在上面的一段代码中,我在声纳中收到“字符串文字表达式应该在等于比较的左侧”这个错误。那么我们该如何避免呢。
I tried this:
我试过这个:
("").equals(!mapData.get("CON_PTY_PARTY_ID"))
But it does not work. Give some advice......
但它不起作用。给点建议......
回答by Kevin W.
You shouldn't surround a blank string with quotes. ("").equals(!mapData.get("CON_PTY_PARTY_ID"))
should just be ! ("".equals(mapData.get("CON_PTY_PARTY_ID")))
您不应该用引号将空白字符串括起来。("").equals(!mapData.get("CON_PTY_PARTY_ID"))
应该只是! ("".equals(mapData.get("CON_PTY_PARTY_ID")))
回答by krodmannix
Kevin W.'s answer is correct but has an error:
凯文 W. 的答案是正确的,但有一个错误:
You shouldn't surround a blank string with quotes.
您不应该用引号将空白字符串括起来。
("").equals(mapData.get("CON_PTY_PARTY_ID"))
should just be
应该只是
!("".equals(mapData.get("CON_PTY_PARTY_ID")))
The above is correct.
以上是正确的。
EDIT:
编辑:
回答by Mark Meuer
Others have pointed out that the way to avoid this error is to use:
其他人指出,避免此错误的方法是使用:
! ("".equals(mapData.get("CON_PTY_PARTY_ID")))
But no one has pointed out whythis matters. The reason the literal should be on the left side of the equals comparison is to avoid the possibility of an exception if the string being compared to it is null.
但没有人指出为什么这很重要。文字应该在等于比较的左侧的原因是为了避免在与之比较的字符串为空时出现异常的可能性。
As written in the question, if the value of mapData.get("CON_PTY_PARTY_ID")
was null
, then the expression would be trying to invoke the equals(..)
method of an object that doesn't exist.That would throw an exception. By putting the literal on the left, then even if the value of mapData.get("CON_PTY_PARTY_ID")
was null
, the method "".equals(...)
would be defined and would not throw an exception. It would simply return false
.
如问题中所写,如果值为mapData.get("CON_PTY_PARTY_ID")
was null
,则表达式将尝试调用不存在的对象的equals(..)
方法。那会抛出异常。通过将文字放在左侧,即使值为mapData.get("CON_PTY_PARTY_ID")
was null
,该方法"".equals(...)
也将被定义并且不会抛出异常。它会简单地返回false
。