繁体   English   中英

为什么Object == null起作用?

[英]Why does Object == null work?

因此,当我们比较对象时,我们使用equals()方法或例如if语句中的类似方法。 如果我们有以下代码

String a = "foo";
String b = "foo";
return a==b

因为a和b引用了不同的对象,我们将得到错误的返回值。 另一方面,

String a = null;
return a == null

我们会成真。 这是为什么?

为什么Object == null起作用?

这真的没有任何意义。 对象不是Java中的值。 你不能这样写。 您只能编写someObjectReference == null

所以当我们比较对象时

我们不是。 往上看。 我们正在比较参考。

我们使用equals()方法,或者例如在if语句中使用类似方法。 如果我们有以下代码

String a = "foo";
String b = "foo";
return a==b

因为a和b引用了不同的对象,我们将得到错误的返回值。

不,我们不会,也不,他们不会。 它将返回true。 试试吧。 字符串文字由Java合并。 只有一个"foo"对象。

另一方面,

String a = null;
return a == null

我们会成真。 这是为什么?

因为引用a值为null,所以==运算符的RHS上的expression的值也为null。 等值=> ==结果为true 请注意, a是引用,而不是对象。

因为两个不同的引用可以指向相同的内容。 然后,对象相等 ,但引用仍然不同。

但是,当引用相同时,我们将只有一个引用。

给出您的示例:

Object o = new Object();
Object o2 = o;
return  o == o2

会导致?!

我认为null表示不指向堆内存中任何内容的变量。因此,如果a = null,则a == null返回true是合理的,因为a不指向任何内容,并且也为null。

另外,

String s1 = new String("test");
String s2 = "test";
String s3 = null;

校验:

s1 instanceof String // true, s1 is String object and we allocated a memory to it.
s2 instanceof String // true, s2 is String object and we allocated a memory to it.
s3 instanceof String // false, because we did not allocate memory to object of String s3

s1 == null           // false, we allocated a memory to the String object s1
s2 == null           // false, we allocated a memory to the String object s2
s3 == null           // true, because even though s3 is of reference type String, it is null

注意:

s3 instanceof null   // Invalid: as instanceof checks from class name. null is not a class

暂无
暂无

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

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