简体   繁体   English

为什么这会引发Null Pointer Exception?

[英]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. listdata引用现在指向2个不同的对象。 Before that assignment, data was set to null and so was list . 在分配之前, data设置为nulllist设置为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.

相关问题 为什么非空列表会引发空指针异常? - Why does a non-empty List throw a Null Pointer Exception? 为什么 java.util.Map.containsKey 会为不支持空键的映射抛出空指针异常? - Why does java.util.Map.containsKey throw a null pointer exception for maps which don't support null keys? 为什么这会导致空指针异常? - Why does this cause a null pointer exception? 为什么在HashSet中添加null不会引发异常,而在TreeSet中添加null会引发异常 - Why adding null in HashSet does not throw Exception,but adding null in TreeSet throw Exception 定时函数抛出空指针异常 - Timed functions throw null pointer exception 为什么ListView.setAdapter(null)不引发空指针异常? - Why doesn't ListView.setAdapter(null) throw a null pointer exception? 为什么来自BluetoothSocket的输入/输出流被评估为非空值,然后引发空指针异常? - Why do input/outputstream from BluetoothSocket get evaluated as NOT null, then throw null pointer exception? 为什么空指针异常不提供null的表达式? - why null pointer exception does not provide the expression that is null? 为什么这段代码会抛出异常? - Why does this code throw an exception? 为什么replaceAll引发异常 - why does replaceAll throw an exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM