如何避免nullpointerexception?

时间:2019-05-26 20:54:40

标签: java nullpointerexception linked-list

// nullpointerexception

公共类节点{

    Object obj;
    Node nextElem;

    public Node(Object obj) {
        this.obj = obj;
        this.nextElem = null;
    }

public Object getObj() {
    return obj;
}

}

公共类LinkedList {

Node firstElem;

    public void addFirst(Object obj) {
        Node first = new Node(obj);
    }

    public Node getFirstElem() {
        return firstElem;
    }

}

公共类应用{     公共静态void主对象(String [] args){

    LinkedList list = new LinkedList();

    list.addFirst("name1");
    list.addFirst("name2");

    System.out.println(list.getFirstElem().getObj()); //nullpointerexception
}

}

0 个答案:

没有答案