package ex;
class Item{
String text = "hello";
}
class A {
Item item;
private A() {}
private static class LazyHolder {
public static final A INSTANCE = new A();
}
public static A getInstance() {
return LazyHolder.INSTANCE;
}
}
public class Main {
public static void main(String[] args) {
A a = A.getInstance();
Item n0 = a.item;
a.item = new Item();
Item n1 = a.item;
a.item.text = "world";
Item n2 = a.item;
if(n0 != null)
{System.out.println(n0.text);}
else{System.out.println("null");};
// This print "null"
System.out.println(n1.text);
// This print "world"
System.out.println(n2.text);
// This print "world"
}
}
您好,我是一名独自学习java的学生。我有一个问题。
如您所见,n1 和 n2 不为空,n0 为空。 并且n1.text和n2.text都有“world”。
所以当我看到这个结果时,我得到了一个结论,但我不知道我认为的是真的。
这是我的问题: 如果某个字段为null,是否表示该字段没有指针?
<小时/>请求:
我可以理解n0“有”指向空的指针吗? n1 和 n2 有指向 Item 类型实例的指针?
最佳答案
If some field have null, Does it mean that the filed has no pointer?
不,不是因为 null pointer仍然是一个指针 - 它只是一个被赋值为 null 的指针。
请记住,分配空指针与完全未初始化有很大不同。例如,以下内容甚至无法编译:
public static void main(String []args){
String s;
System.out.println(s);
}
以下内容将编译,并且它会逐字打印 null
:
public static void main(String []args){
String s = null;
System.out.println(s);
}
尝试使用指定的 null
内容的一些类似示例可能会抛出 NullPointerException
,这实际上是 Stack Overflow 上讨论最多的异常之一。
关于java - Java 中的空值和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59639850/