In Java I am told that when doing a null check one should use == instead of .equals(). What are the reasons for this?
在Java中,我被告知在进行空检查时应该使用==而不是.equals()。这是什么原因?
13 个解决方案
#1
140
They're two completely different things. ==
compares the object reference, if any, contained by a variable. .equals()
checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals
is a method, if you try to invoke it on a null
reference, you'll get a NullPointerException
.
他们是两个完全不同的东西。 ==比较变量包含的对象引用(如果有)。 .equals()检查两个对象是否相等,根据它们的契约是什么相等。根据合同,两个不同的对象实例完全可能“相等”。然后有一个小细节,因为equals是一个方法,如果你尝试在null引用上调用它,你将得到一个NullPointerException。
For instance:
例如:
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
#2
33
if you invoke .equals()
on null
you will get NullPointerException
如果在null上调用.equals(),则会得到NullPointerException
So it is always advisble to check nullity before invoking method where ever it applies
因此,在调用适用的方法之前,始终建议检查nullity
if(str!=null && str.equals("hi")){
//str contains hi
}
Also See
另见
- difference-between-equals-and == in Java
- Java中的equals-between =和==之间的差异
#3
17
In Java 0 or null are simple types and not objects.
在Java 0或null中是简单类型而不是对象。
The method equals() is not built for simple types. Simple types can be matched with ==.
方法equals()不是为简单类型构建的。简单类型可以与==匹配。
#4
11
In addition to the accepted answer (https://*.com/a/4501084/6276704):
除了接受的答案(https://*.com/a/4501084/6276704):
Since Java 1.7, if you want to compare two Objects which might be null, I recommend this function:
从Java 1.7开始,如果你想比较两个可能为null的对象,我推荐这个函数:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
java.util.Objects
This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
此类包含用于对对象进行操作的静态实用程序方法。这些实用程序包括null-safe或null-tolerant方法,用于计算对象的哈希代码,返回对象的字符串以及比较两个对象。
Since: 1.7
自:1.7
#5
3
foo.equals(null)
What happens if foo is null?
如果foo为null会发生什么?
You get a NullPointerException.
你得到一个NullPointerException。
#6
2
If an Object variable is null, one cannot call an equals() method upon it, thus an object reference check of null is proper.
如果Object变量为null,则无法对其调用equals()方法,因此对象引用检查为null是正确的。
#7
2
If you try calling equals on a null object reference, then you'll get a null pointer exception thrown.
如果您尝试在null对象引用上调用equals,那么您将获得抛出的空指针异常。
#8
2
According to sources it doesn't matter what to use for default method implementation:
根据消息来源,默认方法实现使用什么并不重要:
public boolean equals(Object object) {
return this == object;
}
But you can't be sure about equals
in custom class.
但你不能确定自定义类中的equals。
#9
2
If we use=> .equals method
如果我们使用=> .equals方法
if(obj.equals(null))
// Which mean null.equals(null) when obj will be null.
When your obj will be null it will throw Null Point Exception.
当你的obj为null时,它将抛出Null Point Exception。
so we should use ==
所以我们应该使用==
if(obj == null)
it will compare the references.
它会比较参考文献。
#10
1
Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null. In addition == compares reference to an object.
因为equal是从Object类派生的函数,所以此函数比较类的项。如果你使用null,它将返回false原因导致类内容不为null。另外==比较对象的引用。
#11
1
here is an example where str != null
but str.equals(null)
when using org.json
这是一个使用org.json时str!= null但str.equals(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
EDIT: here is the org.json.JSONObject$Null class:
编辑:这是org.json.JSONObject $ Null类:
/**
* JSONObject.NULL is equivalent to the value that JavaScript calls null,
* whilst Java's null is equivalent to the value that JavaScript calls
* undefined.
*/
private static final class Null {
/**
* A Null object is equal to the null value and to itself.
*
* @param object
* An object to test for nullness.
* @return true if the object parameter is the JSONObject.NULL object or
* null.
*/
@Override
public boolean equals(Object object) {
return object == null || object == this;
}
}
#12
0
So I never get confused and avoid problems with this solution:
因此,我从不会感到困惑并避免使用此解决方案的问题
if(str.trim().length() <=0 ) {
// is null !
}
#13
-3
You could always do
你可以随时做
if (str == null || str.equals(null))
This will first check the object reference and then check the object itself providing the reference isnt null.
这将首先检查对象引用,然后检查对象本身,提供引用isnt null。
#1
140
They're two completely different things. ==
compares the object reference, if any, contained by a variable. .equals()
checks to see if two objects are equal according to their contract for what equality means. It's entirely possible for two distinct object instances to be "equal" according to their contract. And then there's the minor detail that since equals
is a method, if you try to invoke it on a null
reference, you'll get a NullPointerException
.
他们是两个完全不同的东西。 ==比较变量包含的对象引用(如果有)。 .equals()检查两个对象是否相等,根据它们的契约是什么相等。根据合同,两个不同的对象实例完全可能“相等”。然后有一个小细节,因为equals是一个方法,如果你尝试在null引用上调用它,你将得到一个NullPointerException。
For instance:
例如:
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
#2
33
if you invoke .equals()
on null
you will get NullPointerException
如果在null上调用.equals(),则会得到NullPointerException
So it is always advisble to check nullity before invoking method where ever it applies
因此,在调用适用的方法之前,始终建议检查nullity
if(str!=null && str.equals("hi")){
//str contains hi
}
Also See
另见
- difference-between-equals-and == in Java
- Java中的equals-between =和==之间的差异
#3
17
In Java 0 or null are simple types and not objects.
在Java 0或null中是简单类型而不是对象。
The method equals() is not built for simple types. Simple types can be matched with ==.
方法equals()不是为简单类型构建的。简单类型可以与==匹配。
#4
11
In addition to the accepted answer (https://*.com/a/4501084/6276704):
除了接受的答案(https://*.com/a/4501084/6276704):
Since Java 1.7, if you want to compare two Objects which might be null, I recommend this function:
从Java 1.7开始,如果你想比较两个可能为null的对象,我推荐这个函数:
Objects.equals(onePossibleNull, twoPossibleNull)
java.util.Objects
java.util.Objects
This class consists of static utility methods for operating on objects. These utilities include null-safe or null-tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
此类包含用于对对象进行操作的静态实用程序方法。这些实用程序包括null-safe或null-tolerant方法,用于计算对象的哈希代码,返回对象的字符串以及比较两个对象。
Since: 1.7
自:1.7
#5
3
foo.equals(null)
What happens if foo is null?
如果foo为null会发生什么?
You get a NullPointerException.
你得到一个NullPointerException。
#6
2
If an Object variable is null, one cannot call an equals() method upon it, thus an object reference check of null is proper.
如果Object变量为null,则无法对其调用equals()方法,因此对象引用检查为null是正确的。
#7
2
If you try calling equals on a null object reference, then you'll get a null pointer exception thrown.
如果您尝试在null对象引用上调用equals,那么您将获得抛出的空指针异常。
#8
2
According to sources it doesn't matter what to use for default method implementation:
根据消息来源,默认方法实现使用什么并不重要:
public boolean equals(Object object) {
return this == object;
}
But you can't be sure about equals
in custom class.
但你不能确定自定义类中的equals。
#9
2
If we use=> .equals method
如果我们使用=> .equals方法
if(obj.equals(null))
// Which mean null.equals(null) when obj will be null.
When your obj will be null it will throw Null Point Exception.
当你的obj为null时,它将抛出Null Point Exception。
so we should use ==
所以我们应该使用==
if(obj == null)
it will compare the references.
它会比较参考文献。
#10
1
Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null. In addition == compares reference to an object.
因为equal是从Object类派生的函数,所以此函数比较类的项。如果你使用null,它将返回false原因导致类内容不为null。另外==比较对象的引用。
#11
1
here is an example where str != null
but str.equals(null)
when using org.json
这是一个使用org.json时str!= null但str.equals(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
EDIT: here is the org.json.JSONObject$Null class:
编辑:这是org.json.JSONObject $ Null类:
/**
* JSONObject.NULL is equivalent to the value that JavaScript calls null,
* whilst Java's null is equivalent to the value that JavaScript calls
* undefined.
*/
private static final class Null {
/**
* A Null object is equal to the null value and to itself.
*
* @param object
* An object to test for nullness.
* @return true if the object parameter is the JSONObject.NULL object or
* null.
*/
@Override
public boolean equals(Object object) {
return object == null || object == this;
}
}
#12
0
So I never get confused and avoid problems with this solution:
因此,我从不会感到困惑并避免使用此解决方案的问题
if(str.trim().length() <=0 ) {
// is null !
}
#13
-3
You could always do
你可以随时做
if (str == null || str.equals(null))
This will first check the object reference and then check the object itself providing the reference isnt null.
这将首先检查对象引用,然后检查对象本身,提供引用isnt null。