繁体   English   中英

Java空检查为什么使用==而不是.equals()

[英]Java null check why use == instead of .equals()

在 Java 中,我被告知在进行 null 检查时应该使用 == 而不是 .equals()。 这是什么原因?

它们是两种完全不同的东西。 ==比较变量包含的对象引用(如果有)。 .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

如果你在null上调用.equals()你会得到NullPointerException

因此,始终建议在调用适用的方法之前检查无效性

if(str!=null && str.equals("hi")){
 //str contains hi
}  

另见

除了接受的答案( https://stackoverflow.com/a/4501084/6276704 ):

从 Java 1.7 开始,如果你想比较两个可能为 null 的对象,我推荐这个函数:

Objects.equals(onePossibleNull, twoPossibleNull)

java.util.Objects

此类由用于对对象进行操作的静态实用程序方法组成。 这些实用程序包括空值安全或空值容忍方法,用于计算对象的哈希码、返回对象的字符串以及比较两个对象。

自:1.7

在 Java 中,0 或 null 是简单类型而不是对象。

方法 equals() 不是为简单类型构建的。 简单类型可以用==来匹配。

Object.equals 是 null 安全的,但是请注意,如果两个对象都为 null,object.equals 将返回 true,因此在使用 object.equals比较。

String firstname = null;
String lastname = null;

if(Objects.equals(firstname, lastname)){
    System.out.println("equal!");
} else {
    System.out.println("not equal!");
}

上面的示例片段将返回相等!

foo.equals(null)

如果 foo 为 null 会怎样?

你得到一个 NullPointerException。

如果 Object 变量为 null,则不能对其调用 equals() 方法,因此 null 的对象引用检查是适当的。

如果我们使用 =>.equals 方法

if(obj.equals(null))  

// Which mean null.equals(null) when obj will be null.

当您的 obj 为 null 时,它将抛出 Null Point Exception。

所以我们应该使用==

if(obj == null)

它将比较参考。

这是一个示例,其中str != nullstr.equals(null)使用org.json

 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




编辑:这里是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;
    }  
}

如果您尝试在空对象引用上调用 equals,那么您将抛出一个空指针异常。

根据消息来源,默认方法实现使用什么并不重要:

public boolean equals(Object object) {
    return this == object;
}

但是你不能确定自定义类中的equals

因为 equal 是从 Object 类派生的函数,所以此函数比较类的项目。 如果将它与 null 一起使用,它将返回 false,因为类内容不为 null。 另外 == 比较对对象的引用。

所以我从不混淆并避免使用此解决方案出现问题:

if(str.trim().length() <=0 ) {
   // is null !
}

我昨晚遇到过这种情况。
我简单地确定:

不存在nullequals() 方法
所以,如果你没有,你不能调用一个不存在的方法
-->>> 这就是为什么我们使用==来检查null的原因

你的代码违反了得墨忒耳定律。 这就是为什么最好重构设计本身。 作为解决方法,您可以使用 Optional

   obj = Optional.ofNullable(object1)
    .map(o -> o.getIdObject11())
    .map(o -> o.getIdObject111())
    .map(o -> o.getDescription())
    .orElse("")

上面是检查对象的层次结构,因此只需使用

Optional.ofNullable(object1) 

如果你只有一个对象要检查

希望这可以帮助 !!!!

你总是可以做

if (str == null || str.equals(null))

这将首先检查对象引用,然后检查对象本身以提供引用不为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM