2014-03-04 26 views
0
public class OrderedArrayList<T extends Comparable<T>> { 

/** This is an array of Objects of type T */ 
private T[] array; 
private int numItems = 0; 
private int itemsRemoved=0; 

@SuppressWarnings("unchecked") 
/** 
* Construct an OrderedArrayList with 10 empty slots. Note the recipe for 
* creating an array with the generic type. You'll want to reuse this 
* recipe in the insert() method. You'll also possibly want to tweak this 
* constructor a bit if you add other instance variables. 
*/ 
public OrderedArrayList() { 
    array = (T[]) new Comparable[10]; 

} 

@SuppressWarnings("unchecked") 
/** 
* _Part 1: Implement this method._ 
* 
* Inserts a new item in the OrderedArrayList. This method should ensure 
* that the list can hold the new item, and grow the backing array if 
* necessary. If the backing array must grow to accommodate the new item, it 
* should grow by a factor of 2. The new item should be placed in sorted 
* order using insertion sort. Note that the new item should be placed 
* *after* any other equivalent items that are already in the list. 
* 
* @return the index at which the item was placed. 
*/ 
public int insert(T item) { 
    if (numItems==0){ 
     array[0]=item; 
     numItems++; 
     return 0; 
    } 
    if (numItems==array.length){ 
     T[] newArray = (T[]) new Comparable[array.length * 2]; 
     for (int i = 0; i < array.length; i++){ 
      newArray[i] = array[i]; 
     } 
     array=newArray; 
    } 
    numItems++; 
    for (int j = numItems-1; j >= 0; j--) { 

     if (array[j].compareTo(item) <= 0){ 
      array[j+1] = item; 
      return j+1; 
     } 

     else{ 
      array[j+1] = array[j]; 

     } 


    } 
    return -1; 
} 

當我試圖與給定的測試,以測試這對於分配這種方法,如果遇到問題中的第二項插入排序在Java中,無法添加第二項?

@Test 
public void removeWithTwoDifferentItems() { 
    int i; 
    OrderedArrayList<String> a = new OrderedArrayList<String>(); 
    a.insert("Hello!"); 
    a.insert("Zeno."); 
    i = a.find("Hello!"); 
    assertEquals("Can't properly find the only string that should be in the list!", 0, i); 
    i = a.remove("Hel"+"lo!"); 
    assertEquals("remove() expecting 1, but got something else", 1, i); 
} 

上面是測試加入,它說的有錯誤插入Zeno。 看起來好像我已經正確地寫了這個,但我不知道如何解決它? 此外,如果數組已滿,陣列應該增長到20,我不知道如果這也是錯誤的,但我主要關心的第二件事插入數組。

+2

「它說在插入Zeno時出現錯誤」我的通靈頭盔今天似乎沒有工作。也許你可以通過告訴我們(通過我的意思是任何其他人有一個破碎的通靈頭盔)來提供幫助,錯誤是什麼? – John3136

+0

你可以給stacktrace的錯誤 –

+0

@RaviKumar我不知道該怎麼做x_x抱歉,我真的是新的編程 – user3304219

回答

0

正常情況下,陣列中當前的項目在array[0]array[numItems - 1](含)之間分佈,其餘數組值爲null。但是,緊接在for循環之前的numItems++之後,陣列中的項目分佈在array[0]array[numItems - 2]之間,因爲新的array[numItems - 1]仍然包含其在增量之前具有的null值。其結果是,當你到達以後if聲明的array[j]第一值是一樣的array[numItems - 1],仍然是null,並試圖調用compareTonull導致NullPointerException,這是你看到的錯誤。

我建議將numItems++聲明移至for循環之後。