2015-06-21 93 views
-2
My code is as follows: 

//Node class (inner class) 
    private class Node 
    { 
     private String command; 
     private String fileName; 
     private int fileSize; 
     private Node next; 
     private Node prev; 

     //constructor of Node 
     private Node(String command, String fileName, int fileSize, Node prev, Node next) 
     { 
      this.command = command; 
      this.fileName = fileName; 
      this.fileSize = fileSize; 
      this.prev = prev; 
      this.next = next; 
     } 
    } 

    private Node head; 
    private Node tail; 
    int size; 

    //constructor of list 
    public ReadInput() 
    { 
     diskSize = 0; 
     head = null; 
     tail = null; 
     size = 0; 
    } 

    public void insert(String command, String fileName, int fileSize) 
    { 

      if (head == null) 
      { 
       head = tail = new Node(command, fileName, fileSize, null, null); 
       size ++; 
      } 

      else 
      { 
       for(Node temp = head; temp != null; temp = temp.next) 
       { 

         temp.next = new Node(command, fileName, fileSize, temp, temp.next.next); 
         temp.next.next.prev = temp.next; 
         size++; 
         if (fileName == temp.fileName) 
          System.out.println("ID already exists!"); 
         break; 

       } 
      }  
    } 

我只是想插入到我的双向链表中。我有另一种方法调用插入与正确的参数添加到链接列表,我没有张贴在这里,因为它是不必要的。第一次插入头是好的,但在第二次插入,同时调试我的程序,我发现我得到一个空指针异常在线temp.next = new Node(command, fileName, fileSize, temp, temp.next.next); 我不明白我哪里会出错哪里有人可以帮忙吗?感谢插入一个双向链表(获得空指针异常)java

+0

你看过http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – John3136

+0

我知道什么是空指针异常......但这并不意味着我可以随时解决它! – Chalupa

+0

你看过“如何解决”部分吗?你的for循环说“temp不是null,所以temp = temp.next(它可以设置temp为空)。 – John3136

回答

0

对于插入的第一要素,开始对空列表如此这般通过IF块

 head = tail = new Node(command, fileName, fileSize, null, null); 

所以head.next = NULL

当您插入第二个元素,代码跳到别的块

 temp.next = new Node(command, fileName, fileSize, temp, temp.next.next); 

在所述第二项目的情况下,

TEMP =头

temp.next = NULL

temp.next.next =>空引用异常(传递到构造函数最后一个参数)

另外,在看你的代码,它似乎像而非将temp.next.next传递给要传递temp.next的构造函数。改变这种说法是

 temp.next = new Node(command, fileName, fileSize, temp, temp.next); 
+0

但为什么我不能传递一个空值给构造函数? – Chalupa

+0

你可以传递一个空值temp.next为null但是当你尝试访问temp.next .next有效地尝试访问null的下一个属性,因此是NRE。 – KnightFox