public class SortedListOfImmutables {
// Assume that I already have constructors that create new objects,
// thus have its own items array.
private Listable[] items;
下面的方法從列表中刪除一個項目。如果列表包含與參數引用的項目相同的項目,它將從列表中刪除。如果該項目不止一次出現在列表中,只會刪除一個實例。如果該項目沒有出現在列表上,那麼這個方法什麼都不做。 @參數itemToRemove指的是當我運行這是從列表中從對象數組中刪除對象
public void remove(Listable itemToRemove) {
Listable[] newList = new Listable[items.length - 1];
int count = 0;
if(items.length == 0){
newList[0] = itemToRemove;
}else {
/*Compares objects. If they are equal, I replace the index of items
* to null. I use int count to make sure that it only makes one object
* null.
*/
for(int i = 0; i < items.length; i++){
while(count == 0){
if(items[i].equals(itemToRemove)){
items[i] = null;
count++;
}
}
}
}
int changeVar = 0;
/* Copy all the objects into my newList array. Wherever items is null,
* skip to the next index of items and put it into newList.
*/
for(int i = 0; i < newList.length; i++){
newList[i] = items[i + changeVar];
if(items[i + changeVar] == null){
changeVar += 1;
newList[i] = items[i + changeVar];
}
}
items = newList;
}
刪除我得到一個超時錯誤的項目。我做錯了什麼,我該如何解決它。注:我不能使用ArrayList,HashSet的,或LinkedList的,
爲什麼不允許使用ArrayList,HashSet或LinkedList? – Iqbal
items.length的值是多少? –
@ Tirupati Rao:limits.length可以有任何價值。 @ Iqbal:在我學習ArrayList,HashSet或LinkedList之前,我的計算機科學類想讓我對它進行硬編碼。 –