1 回答

TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
您忘記包含“add(T toAdd)”和“remove(T toRemove)”方法,當(dāng)我嘗試讓測(cè)試通過(guò)時(shí),這是絕大多數(shù)失敗的根源。(注意:失敗的痕跡會(huì)有所幫助,因?yàn)槟奶砑雍蛣h除需要非常復(fù)雜才能適應(yīng)您似乎想要的設(shè)計(jì))
無(wú)論如何,繼續(xù)修復(fù)我所看到的內(nèi)容。
在第二個(gè)構(gòu)造函數(shù)中,您實(shí)際上從未分配所接收的數(shù)據(jù)。您調(diào)用this.array = (T[]) new Comparable[0];它會(huì)創(chuàng)建一個(gè)類型為 的空數(shù)組Comparable。事實(shí)上,您需要打電話this.array = data才能保留給您的東西。
另一件事,在您的size()方法中,您忘記在 后放置分號(hào)this.size。這往往會(huì)阻止事情過(guò)去。
最后,final private T[] array不能有final,否則你將永遠(yuǎn)無(wú)法添加或刪除元素。
作為獎(jiǎng)勵(lì),以下是我用來(lái)滿足要求并使測(cè)試通過(guò)的方法(帶注釋!?。。゛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
}
}
}
}
附帶說(shuō)明一下,創(chuàng)建SortedArray對(duì)象的調(diào)用確實(shí)應(yīng)該參數(shù)化(使用 <> 例如SortedArray<Integer> arr = new SortedArray<Integer>(5, data);)。
添加回答
舉報(bào)