[英]Why does this throw Null Pointer Exception?
My code : 我的代码:
static List<Object> data;
private void addItem(List<Object> list) {
try {
data = new ArrayList<Object>();
list.add("test");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ListTest test = new ListTest();
test.addItem(data);
}
Above code throws NullPointerException
. 上面的代码抛出
NullPointerException
。 The code below does not throw NPE. 下面的代码不会引发NPE。
static List<Object> data = new Vector<Object>();
private void addItem(List<Object> list) {
try {
list.add("test");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ListTest test = new ListTest();
test.addItem(data);
}
Above code does not throw NullPointerException
. 上面的代码不会抛出
NullPointerException
。 I don't understand the difference between both. 我不明白两者之间的区别。
Even though you passed data
reference to the method, the moment you assign a new list to data
: 即使您将
data
引用传递给该方法,在为data
分配新列表的那一刻:
data = new ArrayList<Object>();
list
and data
reference are now pointing to 2 different objects. list
和data
引用现在指向2个不同的对象。 Before that assignment, data
was set to null
and so was list
. 在分配之前,
data
设置为null
, list
设置为null
。 But after the assignment, only list
is set to null
. 但是分配后,只有
list
设置为null
。 And thus calling list.add()
will result in NPE
. 因此,调用
list.add()
将导致NPE
。
In second case, data
was not null
to begin with. 在第二种情况下,
data
不以null
开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.