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,我不知道如果這也是錯誤的,但我主要關心的第二件事插入數組。
「它說在插入Zeno時出現錯誤」我的通靈頭盔今天似乎沒有工作。也許你可以通過告訴我們(通過我的意思是任何其他人有一個破碎的通靈頭盔)來提供幫助,錯誤是什麼? –
John3136
你可以給stacktrace的錯誤 –
@RaviKumar我不知道該怎麼做x_x抱歉,我真的是新的編程 – user3304219