1 回答

TA貢獻1799條經驗 獲得超6個贊
您忘記包含“add(T toAdd)”和“remove(T toRemove)”方法,當我嘗試讓測試通過時,這是絕大多數失敗的根源。(注意:失敗的痕跡會有所幫助,因為您的添加和刪除需要非常復雜才能適應您似乎想要的設計)
無論如何,繼續修復我所看到的內容。
在第二個構造函數中,您實際上從未分配所接收的數據。您調用this.array = (T[]) new Comparable[0];它會創建一個類型為 的空數組Comparable。事實上,您需要打電話this.array = data才能保留給您的東西。
另一件事,在您的size()方法中,您忘記在 后放置分號this.size。這往往會阻止事情過去。
最后,final private T[] array不能有final,否則你將永遠無法添加或刪除元素。
作為獎勵,以下是我用來滿足要求并使測試通過的方法(帶注釋?。。。゛dd():remove()
public void add(T t) {
if (!(size >= capacity)) { //If there's room...
if (size == 0) //If the array is empty...
array[0] = t; //Add to first index
else
array[size] = t; //Add to next available index
size++;
}
}
public void remove(T element) {
if (size <= 0) //If the array is empty...
return; //Stop here
else {
for (int i = 0; i <= this.size(); i++) { //Linear search front-to-back
if (array[i].equals(element)) { //Find first match
array[i] = null; //Delete it
size--;
if (i != size) { //If the match was not at the end of the array...
for (int j = i; j <= (this.size() - 1); j++)
array[j] = array[j + 1]; //Move everything after the match to the left
}
return; //Stop here
}
}
}
}
附帶說明一下,創建SortedArray對象的調用確實應該參數化(使用 <> 例如SortedArray<Integer> arr = new SortedArray<Integer>(5, data);)。
添加回答
舉報