简体   繁体   中英

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 . The code below does not throw 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 . 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 = new ArrayList<Object>();

list and data reference are now pointing to 2 different objects. Before that assignment, data was set to null and so was list . But after the assignment, only list is set to null . And thus calling list.add() will result in NPE .

In second case, data was not null to begin with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM