直接先看示例代码:
if (Objects.equals(1, req.getRefundDeposit())) {
requisition.setDeductAmount(req.getRefundDepositAmount());
}
也就是使用Objects.equals方法
这是它的全限定名
java.util.Objects#equals
这是它的底层实现
/**
* Returns {@code true} if the arguments are equal to each other
* and {@code false} otherwise.
* Consequently, if both arguments are {@code null}, {@code true}
* is returned and if exactly one argument is {@code null}, {@code
* false} is returned. Otherwise, equality is determined by using
* the {@link Object#equals equals} method of the first
* argument.
*
* @param a an object
* @param b an object to be compared with {@code a} for equality
* @return {@code true} if the arguments are equal to each other
* and {@code false} otherwise
* @see Object#equals(Object)
*/
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
可以看到它的javaDoc解释:
如果两个元素都为null,则返回true。如果其中一个为null,则返回false
有了这个方法,再也不要使用==来判断相等了,再也不会出空指针了