什么时候返回null?
问题描述:
有主类和2个示例类。一个延伸HashMap
。什么时候返回null?
本公司主营:
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);
}
}
现在看看控制台输出:
正:
PositiveExample @ 2a139a55
假
负:
{}
假
而且注意空虚{}
。与标准类输出中的[email protected]
相反。
基于HashMap
的输出类说this
不是null
,但这就是它的行为方式,不是。检查一下你自己。
我对Java构建1.8.0_60-B27,Ubuntu的14.04 64位。
答
你知道在返回null的类中有
this
的任何例子吗?
不,这不可能发生。期。代码中的某处存在一个错误,它令您觉得this
为空,但事实并非如此。如果你觉得不然,那么你会想发布你的相关代码来证明你的假设是正确的。
编辑:我刚刚发现了一个duplicate question即进入进一步的细节。
只是一个没有任何代码的一般问题,因为它不是必需的。
你是正确的,回答直接的问题,在你的编辑以上后,无需代码。但是,如果你想找到你的代码真正问题,那就是给你的错误想法,this
是空的,然后根据我在评论中指出,你要创建和发布您Minimal, Complete, and Verifiable example。
编辑2
感谢你更新你的代码。控制台的输出结果是完全一样的人们所期望的:
Positive:
[email protected] // 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覆盖,并返回地图的内容,这里什么都没有。
当您没有发布任何代码时很难解决。 – Tunaki
如果没有您发布的相关代码,我不确定您希望我们如何理解您的问题或您的代码。请通过[游览],[帮助]和[如何提出一个很好的问题](http://*.com/help/how-to-ask)部分来查看本网站的工作原理并帮助您改善您当前和未来的问题,这可以帮助您获得更好的答案。 –
那么,这个问题并不需要比我已经发布的更多的代码,以我的理解。问题是为什么这返回null。简单。它不应该,对吧? – Tomasz