这个 return 什么时候为空?

When does this return null?

有主要 class 和 2 个示例 class。一个扩展 HashMap.

主线:

public class Main {
    public static void main(String[] args) {
        System.out.println("Positive:");
        PositiveExample positiveExample = new PositiveExample();
        positiveExample.printThis();
        System.out.println("Negative:");
        NegativeExample negativeExample = new NegativeExample();
        negativeExample.printThis();
    }
}

标准款:

public class PositiveExample {
    void printThis() {
        System.out.println(this);
        System.out.println(this == null);
    }
}

以及基于 HashMap 的。

import java.util.HashMap;

public class NegativeExample extends HashMap {
    void printThis() {
        System.out.println(this);
        System.out.println(this == null);
    }
}

现在看看控制台输出:

Positive:
PositiveExample@2a139a55
false
Negative:
{}
false

并注意空的 {}。与标准 class' 输出中的 PositiveExample@2a139a55 相反。

基于 HashMap 的 class 输出说 this 不是 null,但这就是它的行为方式,不是吗。自己看吧。

我正在使用 Java build 1.8。0_60-b27、Ubuntu 14.04 64 位。

Do you know any examples of this in a class returning null?

不,这不可能发生。时期。您在代码中的某处有一个错误,使您误以为 this 为空,但事实并非如此。如果您不这么认为,那么您将需要 post 您的相关代码来证明您的假设是正确的。

编辑:我刚刚找到了一个 duplicate question,其中包含更多详细信息。

Just a general question without any code, as it's not needed.

你是对的,要回答上面 edited post 中的直接问题,不需要代码。但是,如果您想在代码 中找到真正的 问题,即给您错误想法 this 为 null 的问题,那么正如我在评论中指出的那样,您我会想要创建和 post 你的 Minimal, Complete, and Verifiable example.


编辑 2
感谢您更新代码。您的控制台输出完全符合预期:

Positive:                       
pkg.PositiveExample@659e0bfd  // this is the default toString of a class that has not overridden toString
false                         // as expected, this is NOT null
Negative:
{}                            // this is the toString returned from the parent class, HashMap, specifically an EMPTY HashMap
false                         // as expected, this is NOT null

问题与您对toString()方法的理解(或误解)有关。如果您不覆盖该方法或有一个覆盖它的超级 class,它默认为在对象 class 中找到的基本 toString() 方法,然后它 returns class 名称和对象的哈希码。如果您确实覆盖了它或者有一个父 class 覆盖了它,它 return 会按照告诉 return 的任何内容进行。这里 HashMap 覆盖,并且 returns 是 Map 的 contents,这里 nothing.