Java.lang.NullPointerException错误。检查空对象

时间:2014-05-31 05:48:49

标签: java nullpointerexception null linked-list

所以我在这里尝试做的是通过if(x.next==null)来检查某个对象是否存在,并且我因为不能让我访问某个对象而收到错误null对象。尝试修改对象时,我也会遇到同样的错误。 x.next=y

代码很简单,只是为了实现链接列表。 谢谢!

//import SingleLinkedList1.Node;

public class SingleLinkedList2 implements ISimpleList2 {

private class Node
{   int    value;
    Node   next; }

private Node first;
private Node last;    


public void insertFront(int item) {
    // TODO Auto-generated method stub
    Node oldfirst = first;

    // Create the new node
    Node newfirst = new Node();
    newfirst.value = item;
    newfirst.next = oldfirst;

    // Set the new node as the first node
    first = newfirst;
    if(oldfirst.next==null){
        last=first;
    }
}

public int removeFront() {
    // TODO Auto-generated method stub
    // Save the previous first
    Node oldfirst = first;

    if(oldfirst.next==null){
        last=null;
    }

    // Follow the first's node (possibly empty)
    // and set the first to that pointer
    first = oldfirst.next;

    // Return the value of old first 
    return oldfirst.value;

}

public void insertEnd(int item) {
    // TODO Auto-generated method stub


    Node newLast=new Node();
    newLast.value=item;
    last.next=newLast;

    last=newLast;

}

public int removeEnd() {
    // TODO Auto-generated method stub
    Node oldLast=last;
    Node check=new Node();
    check=first;
    while(check.next!=last ){
        check=check.next;
    }
    last=check;

    return oldLast.value;

}

public boolean isEmpty()
{
    if(first.next==null){
        return true;
    }
    else{
        return false;
    }
}


}

2 个答案:

答案 0 :(得分:0)

我认为你应该检查x可以为null ..

与代码f(x == null)类似,因为如果x为空,那么您将获得NullPointException

答案 1 :(得分:0)

这很常见。 您必须确保对象本身不为空。

在您的检查if(x.next==null)中,对x.next的评估会抛出NullPointerException,因为x本身是空的。

E.g。在isEmpty方法中,您必须检查是否(first == null)