Possible Duplicate:
Difference between these two conditions?可能重复:这两个条件之间的差异?
I am doing some code cleanup and NetBeans made a suggestion to change
我正在做一些代码清理,NetBeans提出了改变的建议
if(!billAddress1.equals(""))
to if (!"".equals(billAddress1))
.
if(!billAddress1.equals(“”))if if(!“”。equals(billAddress1))。
What is the difference between the two, and the advantages of using the suggested version over the readability of the original version?
两者之间有什么区别,以及使用建议版本优于原始版本的可读性的优势?
6 个解决方案
#1
7
billAddress1.equals("")
will cause a NullPointerException if billAddress1
is null
, "".equals(billAddress1)
wont.
如果billAddress1为null,则billAddress1.equals(“”)将导致NullPointerException,“”。equals(billAddress1)不会。
#2
3
// Could cause a NullPointerException if billAddress1 is null
if(!billAddress1.equals(""))
// Will not cause a NullPointerException if billAddress1 is null
if (!"".equals(billAddress1))
#3
3
!"".equals(billAddress1)
will never cause an NPE
, so it allows a more compact syntax by allowing to get rid of the billAddress1 == null
that would otherwise be required.
!“”。equals(billAddress1)永远不会导致NPE,所以它允许摆脱billAddress1 == null,否则将需要更紧凑的语法。
#4
2
The latter will not cause a Null pointer exception if the value is null.
如果值为null,后者将不会导致Null指针异常。
#5
2
One saves you from NPE as others have pointed out. But if you are sure it's not going to be null then the better way to check if a string is empty is to use the String.isEmpty()
method, that's what the code seems to be trying to do.
正如其他人指出的那样,一个可以让你远离NPE。但是如果你确定它不会为null,那么检查字符串是否为空的更好方法是使用String.isEmpty()方法,这就是代码似乎试图做的事情。
#6
1
The first one has a potential to cause NullPointerException.
第一个可能会导致NullPointerException。
#1
7
billAddress1.equals("")
will cause a NullPointerException if billAddress1
is null
, "".equals(billAddress1)
wont.
如果billAddress1为null,则billAddress1.equals(“”)将导致NullPointerException,“”。equals(billAddress1)不会。
#2
3
// Could cause a NullPointerException if billAddress1 is null
if(!billAddress1.equals(""))
// Will not cause a NullPointerException if billAddress1 is null
if (!"".equals(billAddress1))
#3
3
!"".equals(billAddress1)
will never cause an NPE
, so it allows a more compact syntax by allowing to get rid of the billAddress1 == null
that would otherwise be required.
!“”。equals(billAddress1)永远不会导致NPE,所以它允许摆脱billAddress1 == null,否则将需要更紧凑的语法。
#4
2
The latter will not cause a Null pointer exception if the value is null.
如果值为null,后者将不会导致Null指针异常。
#5
2
One saves you from NPE as others have pointed out. But if you are sure it's not going to be null then the better way to check if a string is empty is to use the String.isEmpty()
method, that's what the code seems to be trying to do.
正如其他人指出的那样,一个可以让你远离NPE。但是如果你确定它不会为null,那么检查字符串是否为空的更好方法是使用String.isEmpty()方法,这就是代码似乎试图做的事情。
#6
1
The first one has a potential to cause NullPointerException.
第一个可能会导致NullPointerException。