String str = "abc";
像下面这样比较这个字符串变量。
if(str.equals("abc")) {}
如果 str
是 null
,它会导致明显抛出 java.lang.NullPointerException
。
为避免这种情况,可能会强制执行额外的空值检查。比如,
if(str != null && str.equals("abc")) {}
我觉得很丑。更好的可以重写如下。
if("abc".equals(str)) {}
这永远不会抛出 java.lang.NullPointerException
,即使 str
为 null
。此外,object equals null
永远不会为真。
然而,当条件表达式像这样反转时,不能使用最后一种情况,
if(!"abc".equals(str)) {
System.out.println(str.length());
}
如果 str
为 null
,这将导致 if
block 内的 java.lang.NullPointerException
。
如果不像下面这样重写条件语句,是否可以以某种方式避免这种情况?
if(str != null && !"abc".equals(str)) {}
这简直丑陋且不可读。
虽然该示例使用了一个String
对象,但它可能是一个更复杂的对象。
最佳答案
另一种方法是使用 Java 8 可选包装器
Optional<Customer> optional = findCustomer();
if (optional.isPresent()) {
Customer customer = maybeCustomer.get();
... use customer ...
}
else {
... deal with absence case ...
}
关于java - 在 Java 中表示 "Both not null and not equal"的实用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31744411/