2012-09-16 37 views
1

作爲練習練習,我創建了自己的泛型類,基本上是ArrayList的副本。雖然與JUnit測試的類,我遇到一個NullPointerException錯誤添加方法:創建類ArrayList類時的NullPointerException

public void add(int index, T element) { 
    if (index > this.size() || index < 0) { 
     throw new IndexOutOfBoundsException(); 
    } 

    if (this.size() == data.length) { 
     //^This is the line that the error points to 
     resize(this.data); 
    } 

    for (int i = index; i < this.size; i++) { 
     this.data[i + 1] = this.data[i]; //fix 
    } 

    this.data[index] = element; 
    size++; 
} 

亂搞與班上後,我無法揣摩出錯誤的來源。我可以提供所需的任何細節/班級的其他部分。關於問題所在位置的任何指導都會很棒。謝謝。

的類的構造:

MyArrayList(int startSize) { 
    // round the startSize to nearest power of 2 
    int pow2 = 1; 
    do { 
     pow2 *= 2; 
    } while (pow2 < startSize); 

    startSize = pow2; 
    this.size = 0; 
    T[] data = (T[]) new Object[startSize]; 
} 

以下測試情況下測試的尺寸,但是,當它試圖添加元素遇到錯誤:

public void testSize() { 
    MyArrayList<Integer> test = new MyArrayList<Integer>(); 
    ArrayList<Integer> real = new ArrayList<Integer>(); 
    assertEquals("Size after construction", real.size(), test.size()); 
    test.add(0,5); 
    real.add(0,5); 
    assertEquals("Size after add", real.size(), test.size()); 
} 
+2

好,'this'不能'null',所以'data'必須是吧? –

回答

6
T[] data = (T[]) new Object[startSize]; 

初始化局部變量data。你不想要的。

將其更改爲以下,以確保您初始化實例變量 -

this.data = (T[]) new Object[startSize]; 
+0

+1這是開啓(並注意)關於未使用變量的警告的好時機。 –

0

我的NPE是上你剛纔提到的那只是因爲datanull。你在哪裏初始化data

也許當您創建CustomArrayList時,您並未初始化您的內部陣列data

data intialisation是問題所在。它應該是
this.data = (T[])new Object[startSize];

+0

該數據是在構造函數中,我編輯原始帖子添加到構造函數 – user1547050

+0

你可以發佈你的構造函數和測試用例嗎? – basiljames

相關問題