为什么对象== null起作用



因此,当我们比较对象时,我们使用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引用不同的对象而将false返回给我们。

不,我们不会,不,他们不会。它将返回正确。尝试一下。字符串文字由Java汇总。只有一个"foo"对象。

另一方面,

String a = null;
return a == null

我们会成真。为什么是?

因为参考 a的值为null,因此表达式在==运算符的RHS上的值也是。相等值=> ==的结果为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

最新更新