Java null 检查为什么使用 == 而不是 .equals() [英] Java null check why use == instead of .equals()

查看:42
本文介绍了Java null 检查为什么使用 == 而不是 .equals()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,有人告诉我在进行空检查时应该使用 == 而不是 .equals().造成这种情况的原因是什么?

In Java I am told that when doing a null check one should use == instead of .equals(). What are the reasons for this?

推荐答案

它们是两个完全不同的东西.== 比较变量包含的对象引用(如果有)..equals() 检查两个对象是否相等,根据它们的相等含义的约定.根据合约,两个不同的对象实例完全有可能相等".然后还有一个小细节,因为 equals 是一个方法,如果你尝试在 null 引用上调用它,你会得到一个 NullPointerException.

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.

例如:

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

这篇关于Java null 检查为什么使用 == 而不是 .equals()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆