2015-05-06 208 views
0
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的,

+0

爲什麼不允許使用ArrayList,HashSet或LinkedList? – Iqbal

+0

items.length的值是多少? –

+0

@ Tirupati Rao:limits.length可以有任何價值。 @ Iqbal:在我學習ArrayList,HashSet或LinkedList之前,我的計算機科學類想讓我對它進行硬編碼。 –

回答

1

你的第二個for循環更改爲

int j=0; 
for (int i = 0; i < items.length; i++) { 
     if (items[i] ! = null) { 
      newList[j] = items[i]; 
      j++; 
     } 
} 

這應該爲你工作。

編輯:

取出while (count==0)循環,這是創建超時。

+0

這是一個很好的選擇,但是當我運行我的教授測試時,我仍然收到「超時錯誤」 –

+0

在上面的答案中檢查我的編輯,它應該對您有所幫助。 while循環正在創建超時。只要刪除它。希望這可以幫助。 – Iqbal

+0

如果我刪除了我的While循環,那麼如果我有重複的對象,我會有多個空值?我應該從一個對象數組中刪除一個特定的對象,但是如果有多個對象是相同的,我只能刪除其中的一個。 –