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

问题

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

#1 热门回答(145 赞)

它们是两个完全不同的东西。==比较变量所包含的对象引用(如果有的话)..equals()检查以查看两个对象是否根据它们的契约相等于什么相等。根据合同,两个不同的对象实例完全可能"相等"。然后有一个小细节,因为equals是一个方法,如果你试图在null参考上调用它,你将获得aNullPointerException。

例如:

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 赞)

如果你调用.equals()onnull,你将获得NullPointerException

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

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

//str contains hi

}

另见

Java中的equals-between =和=之间的差异

#3 热门回答(17 赞)

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值