栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java null检查为什么使用==代替.equals()

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;    }    }Foo f1 = new Foo(5);Foo f2 = new Foo(5);System.out.println(f1 == f2);// outputs false, they're distinct object instancesSystem.out.println(f1.equals(f2));// outputs true, they're "equal" according to their definitionFoo f3 = null;System.out.println(f3 == null);// outputs true, `f3` doesn't have any object reference assigned to itSystem.out.println(f3.equals(null));// Throws a NullPointerException, you can't dereference `f3`, it doesn't refer to anythingSystem.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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/385118.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号