有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);
}
}
现在看一下控制台输出:
正:
PositiveExample @ 2a139a55
假
阴性:
{}
假
注意空{}
。与标准类'输出中的PositiveExample@2a139a55
相反。
基于HashMap
的类输出显示this
不是null
,但这就是它的行为方式,不是。自己检查一下。
我在Java build 1.8.0_60-b27,Ubuntu 14.04 64 bit。
答案 0 :(得分:3)
您是否知道在返回null的类中
this
的任何示例?
不,这不可能发生。期。您在代码中的某个地方有一个错误让您误以为this
为空,但事实并非如此。如果您不这么认为,那么您需要发布相关代码以证明您的假设是正确的。
编辑:我刚发现duplicate question进一步了解详情。
只是一个没有任何代码的一般性问题,因为它不需要。
您是正确的,要回答上面已修改帖子中的直接问题,不需要任何代码。但是,如果您想在代码中找到真正的问题,那就是错误地认为this
为空的那个,那么就像我在评论中提到的那样,你会想要创建并发布您的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的内容,这里没有。