【问题标题】:When does this return null?这什么时候返回null?
【发布时间】:2015-09-26 11:33:37
【问题描述】:

有 Main 类和 2 个示例类。一个扩展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);
    }
}

现在看看控制台输出:

正面:
正例@2a139a55

否定:
{}
假的

注意空的{}。与标准类输出中的 PositiveExample@2a139a55 不同。

基于HashMap 的类输出显示this 不是null,但这就是它的行为方式,不是吗。自己检查一下。

我正在使用 Java build 1.8.0_60-b27,Ubuntu 14.04 64 位。

【问题讨论】:

  • 不发布任何代码时很难修复。
  • 您的问题没有什么可解决的。你在说“我有问题,你能解决它吗?”您对我们有什么期望?
  • 这就是创建minimal reproducible example 可以提供帮助的地方。它迫使您最小化您的代码,直到您拥有能够重现您的错误的最小代码。这是一个很棒的工具,不仅对我们,这里的帮助者,而且对你,提问者,因为它允许你暴露你的错误。我再次敦促您尝试创建一个。
  • “基于 HashMap 的类输出表明这不是空值,但它的行为方式就是这样,不是吗。” 这对我来说毫无意义。该输出显示 HashMap 为空。为什么你认为 thisnull 或表现得像那样?
  • 顺便说一句,如果你真的尝试打印null,你可以轻松测试你会得到什么:你会得到"null",而不是{}

标签: java this


【解决方案1】:

您知道在返回 null 的类中 this 的任何示例吗?

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

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

只是一个没有任何代码的一般问题,因为它不是必需的。

你是对的,要回答上面已编辑帖子中的直接问题,不需要代码。但是,如果您想在代码中找到真正的问题,即让您错误地认为this 为空的问题,那么正如我在 cmets 中所指出的,您需要创建并发布您的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() 方法的理解(或误解)有关。如果您没有覆盖该方法或有一个覆盖它的超类,它默认为在 Object 类中找到的基本 toString() 方法,然后它返回类名和对象的 hashCode。如果您确实覆盖它或有一个覆盖它的父类,它会返回它被告知返回的任何内容。这里 HashMap 覆盖并返回 Map 的 内容,这里 nothing

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 2012-06-03
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多