2011-03-27 105 views
0

我有我的自定義類的對象數組,我想刪除一個隨機對象(由某些條件選擇)。我如何做到這一點,並保持陣列的秩序?自然,會有向左移動的元素,但我不完全刪除元素部分,需要幫助來制定邏輯。這是我在做什麼,但它不能正常工作:(從數組中刪除對象

 public static void deleteRecord(Customer[] records, int AccId){ 
     int pos=0; // index 
     boolean found = false; 
     for (int i=0; i<count; i++){ // count is the number of elements in the array 
      if (records[i].get_accountid()==AccId){ 
       found = true; 
       pos = i; 
       break; 
      } 
     } 
     if (!found) 
      System.out.println("The Record doesn't exist"); 

     for (int j=pos+1; j<count; j++) { 
      records[j-1]= records[j]; 
      } 
+4

如果您打算隨機刪除元素,通常應該使用列表。 – 2011-03-27 16:04:54

+0

可能的重複[如何從java中的數組中刪除對象?](http://stackoverflow.com/questions/112503/how-do-i-remove-objects-from-an-array-in-java) – McDowell 2011-05-09 10:26:02

回答

4

你可以只轉移的元素到左邊,因爲這將覆蓋要刪除的項目。

public void remove(Object[] a, int index) { 
    for (int i = index + 1; i < a.length && a[i] != null; i++) { 
     a[i - 1] = a[i]; 
    } 
} 

假設第一null表示元素的結束。

當然,這是O(n)的時間和有像鏈表,可以刪除元素在O(1)時間的數據結構。

+3

...但在LinkedList中,如果它不是在其中一個端點上,你仍然需要'O(n)'來查找要刪除的元素。 – 2011-03-27 16:45:45

+0

我編輯了這個問題。我的代碼似乎不工作:/ – dawnoflife 2011-03-27 16:54:39

+0

啊,真的!我想,如果你在一個迭代器內,你可以在不斷的時間內去除元素? – 2011-03-27 16:55:38

1

使用List集合e.g:

List<String> list = new ArrayList<String>(); 
int toDelete = getRandomIndex(lst.size()); //your own implementation 
if (toDelete >= 0) { 
    list.remove(toDelete); // it'll remove and shift elements 
} 

文檔中關於List.remove(INT):

移除此列表中指定位置 元素(可選 操作)。將任何隨後的 元素向左移(從其索引中減去一個 )。返回從 列表中刪除的 元素。

+0

不幸的是不允許使用列表收集。我編輯了這個問題......我的代碼似乎沒有工作。幫助將不勝感激 – dawnoflife 2011-03-27 16:59:10

2

不幸的是,你不能只從數組中刪除一個元素,而不是沒有留下空的索引或創建一個新的數組。我會創建一個新的數組,並使用System.arraycopy來簡化對元素的複製。喜歡的東西:

Object[] newArr = new Object[arr.length-1]; 
System.arraycopy(arr,0,newArr,0,index); 
System.arraycopy(arr,index+1, newArr, index, newArr.length - index); 
return newArr; 

哪裏arr是你原來的陣列和index是刪除隨機指數。基本上,它將所有元素複製到要刪除的索引處,然後複製索引後面的所有元素。爲了簡單起見,您可以將其包裝在單獨的方法中。 (而不是使用arraycopy,你可以使用兩個for-loop來完成同樣的事情)。

我強烈建議其他人必須使用List,這可以簡化添加和刪除元素。

+0

我們不允許使用列表集合來完成此任務 – dawnoflife 2011-03-27 16:58:28

+0

note注意System.arraycopy比手動複製數組更快,因爲它本身實現。 – MeBigFatGuy 2011-03-27 18:51:07