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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4501061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 18:05:32  来源:igfitidea点击:

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

javanull

提问by Jim Jeffries

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()。造成这种情况的原因是什么?

采纳答案by T.J. Crowder

They're two completely different things. ==compares the object reference, if any, contained by a variable. .equals()checks to see if two objects are equalaccording 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 equalsis a method, if you try to invoke it on a nullreference, 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

回答by Jigar Joshi

if you invoke .equals()on nullyou will get NullPointerException

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

So it is always advisble to check nullity before invoking method where ever it applies

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

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

Also See

另见

回答by Jé Queue

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 的对象引用检查是正确的。

回答by Nick Orton

foo.equals(null)

What happens if foo is null?

如果 foo 为空会发生什么?

You get a NullPointerException.

你得到一个 NullPointerException。

回答by A_M

If you try calling equals on a null object reference, then you'll get a null pointer exception thrown.

如果您尝试在空对象引用上调用 equals,则会抛出空指针异常。

回答by danny.lesnik

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。另外 == 比较对对象的引用。

回答by DixonD

According to sourcesit 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 equalsin custom class.

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

回答by user523859

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() 不是为简单类型构建的。简单类型可以与 == 匹配。

回答by Kevin Orriss

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.

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

回答by AKT

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.

它将比较参考。