2014-11-04 134 views
1

所以我得到這個nullpointerexception。我知道它是由什麼引起的,我只是無法看到代碼中的內容。爲什麼我會得到這個空指針異常?

import java.util.*; 

public class NoDuplicatesQueueWilson<T> implements NoDuplicatesQueueInterfaceWilson<T> 
{ 
private int MAX_QUEUE = 5; // Default array size, small for testing purposes 
private T[] items; // The array of the queue. 
private int front; // The first entered item of a queue. 
private int back; // The last entered item of a queue. 
private int count; // A counter. 

public NoDuplicatesQueueWilson() // Default constructor 
{ 
    T [] items = (T[]) new Object[MAX_QUEUE]; 
    front = 0; 
    back = MAX_QUEUE-1; 
    count = 0; 
} 

// Begin Queue Operations 
// isEmpty() checks the array to determine if there is an items in it. 
public boolean isEmpty() 
{ 
    return count == 0; 
} 

// isFull() checks to see if the array is full or not. 
public boolean isFull() 
{ 
    return count == MAX_QUEUE; 
} 

// enqueue(Object newItem) adds items to the back of the queue if it is not full. 
// If it is full, it will double the size of the array of items, 
// and re-create the array, adding the item onto the new array. 
public void enqueue(T newItem) { 
    if(!isFull()) 
    { 
    back = (back+1) % (MAX_QUEUE); 
    items[back] = newItem; 
    ++count; 
    } 
    else 
    { 
    MAX_QUEUE = MAX_QUEUE * 2; 
    System.out.println("The array was full. We've doubled the size."); 
    T [] items = (T[]) new Object[MAX_QUEUE]; 
    back = (back+1) % (MAX_QUEUE); 
    items[back] = newItem; 
    ++count; 
    } // End if 
} // End Enqueue 

當我在我的驅動器程序運行(測試數據),該異常發生在給定的代碼的第43行(包含方法和構造我的主類),這是在我的排隊的中間方法。具體是這條線:

items[back] = newItem; 

任何建議我可能需要做或正在尋找,看看我的錯誤是哪裏?

+0

你能解釋一下=(back + 1)%(MAX_QUEUE);?你是怎麼想出來的? – 2014-11-04 02:59:31

回答

2

在構造函數中,您並未初始化T [] items,但您正在創建新的局部變量。它應該是

public NoDuplicatesQueueWilson() // Default constructor 
{ 
    items = (T[]) new Object[MAX_QUEUE]; // notice the difference 
    front = 0; 
    back = MAX_QUEUE-1; 
    count = 0; 
} 

編輯:還請enqueue方法檢查代碼else一部分。

+0

此外,排隊的其他部分出現相同的錯誤。 – 2014-11-04 03:04:55

1

在你的構造,該行分配給一個局部變量,而不是一個實例變量:

T [] items = (T[]) new Object[MAX_QUEUE]; 

您可以this.items訪問實例變量items

this.items = (T[]) new Object[MAX_QUEUE]; 

你也可以只使用items = ...,因爲在這種情況下不存在歧義。

同樣的錯誤也在enqueue(T newItem)方法T [] items = ...

相關問題