【发布时间】: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 为空。为什么你认为
this是null或表现得像那样? -
顺便说一句,如果你真的尝试打印
null,你可以轻松测试你会得到什么:你会得到"null",而不是{}。