在Java中我被告知在进行空检查时应该使用==而不是.equals()。这是什么原因?
答案 0 :(得分:163)
他们是完全不同的两件事。 ==
比较变量包含的对象引用(如果有)。 .equals()
检查两个对象是否相等根据他们的平等意味着什么。根据合同,两个不同的对象实例完全可能“相等”。然后有一个小细节,因为equals
是一种方法,如果您尝试在null
引用上调用它,您将获得NullPointerException
。
例如:
class Foo {
private int data;
Foo(int d) {
this.data = d;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
return ((Foo)other).data == this.data;
}
/* In a real class, you'd override `hashCode` here as well */
}
Foo f1 = new Foo(5);
Foo f2 = new Foo(5);
System.out.println(f1 == f2);
// outputs false, they're distinct object instances
System.out.println(f1.equals(f2));
// outputs true, they're "equal" according to their definition
Foo f3 = null;
System.out.println(f3 == null);
// outputs true, `f3` doesn't have any object reference assigned to it
System.out.println(f3.equals(null));
// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anything
System.out.println(f1.equals(f3));
// Outputs false, since `f1` is a valid instance but `f3` is null,
// so one of the first checks inside the `Foo#equals` method will
// disallow the equality because it sees that `other` == null
答案 1 :(得分:33)
如果您在.equals()
上调用null
,您将获得NullPointerException
因此,在调用适用的方法之前,始终建议检查nullity
if(str!=null && str.equals("hi")){
//str contains hi
}
另见
答案 2 :(得分:17)
在Java 0或null中是简单类型而不是对象。
方法equals()不是为简单类型构建的。简单类型可以与==。
匹配答案 3 :(得分:15)
除了接受的答案(https://stackoverflow.com/a/4501084/6276704):
从Java 1.7开始,如果你想比较两个可能为null的对象,我推荐这个函数:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
此类包含用于操作的静态实用程序方法 对象。这些实用程序包括null-safe或null-tolerant方法 用于计算对象的哈希码,返回一个字符串 对象,并比较两个对象。
自: 1.7
答案 4 :(得分:3)
foo.equals(null)
如果foo为null,会发生什么?
你得到一个NullPointerException。
答案 5 :(得分:2)
如果Object变量为null,则无法对其调用equals()方法,因此对象引用检查为null是正确的。
答案 6 :(得分:2)
如果尝试在空对象引用上调用equals,则会抛出空指针异常。
答案 7 :(得分:2)
根据sources,默认方法实现的用途无关紧要:
public boolean equals(Object object) {
return this == object;
}
但您无法确定自定义类中的equals
。
答案 8 :(得分:2)
如果我们使用=> .equals方法
if(obj.equals(null))
// Which mean null.equals(null) when obj will be null.
当你的obj为null时,它将抛出Null Point异常。
所以我们应该使用==
if(obj == null)
它将比较参考文献。
答案 9 :(得分:2)
Object.equals是null安全的,但是请注意,如果两个对象为null,则object.equals将返回true,因此请确保在使用object之前检查要比较的对象是否为null(或保留null值) .equals进行比较。
String firstname = null;
String lastname = null;
if(Objects.equals(firstname, lastname)){
System.out.println("equal!");
} else {
System.out.println("not equal!");
}
上面的示例代码片段将返回等于!
答案 10 :(得分:1)
因为equal是从Object类派生的函数,所以此函数比较类的项。如果你使用null,它将返回false原因导致类内容不为null。另外==比较对象的引用。
答案 11 :(得分:1)
以下是使用n <- 1e5
set.seed(24)
df1 <- data.frame(query_string = sample(sprintf("%06d", 100:1000),
n, replace=TRUE), id.x = sample(1:n),
s_val = sample(paste0("F", 400:700), n,
replace=TRUE), id.y = sample(100:3000, n, replace=TRUE),
ID_col_n = sample(100:1e6, n, replace=TRUE), total_id = 1:n)
str != null
但str.equals(null)
的示例
org.json
修改强>
这是org.json.JSONObject$Null类:
JSONObject jsonObj = new JSONObject("{field :null}");
Object field = jsonObj.get("field");
System.out.println(field != null); // => true
System.out.println( field.equals(null)); //=> true
System.out.println( field.getClass()); // => org.json.JSONObject$Null
答案 12 :(得分:0)
所以我从不会感到困惑并避免使用此解决方案的问题:
if(str.trim().length() <=0 ) {
// is null !
}
答案 13 :(得分:0)
昨晚我遇到了这种情况。
我简单地确定为:
不存在 null 的 equals()方法
的原因
因此,如果没有,您将无法调用一种不存在的方法
->>>这就是为什么我们使用 == 来检查 null
答案 14 :(得分:0)
您的代码违反了得墨meter耳定律。这就是为什么最好重构设计本身。解决方法是,您可以使用Optional
obj = Optional.ofNullable(object1)
.map(o -> o.getIdObject11())
.map(o -> o.getIdObject111())
.map(o -> o.getDescription())
.orElse("")
上面是检查对象的层次结构,因此只需使用
Optional.ofNullable(object1)
如果您只需要检查一个对象
希望这有帮助!!!!
答案 15 :(得分:-3)
你可以随时
if (str == null || str.equals(null))
这将首先检查对象引用,然后检查对象本身,提供引用isnt null。