2015-06-21 94 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