从数组中删除对象

时间:2011-03-27 16:02:50

标签: java algorithm

我有一个自定义类的对象数组,我想删除一个随机对象(按某些条件选择)。我该怎么做并保持阵列的有序?自然地,会向左移动元素但我不完全删除元素部分并需要帮助制定逻辑。这是我正在做的,但因为它无法正常工作:(

     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];
          }

3 个答案:

答案 0 :(得分: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)时间,并且像LinkedList这样的数据结构可以在O(1)时间内删除元素。

答案 1 :(得分: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循环来完成同样的事情。)

我强烈建议其他人必须使用List,这样可以简化添加和删除元素。

答案 2 :(得分:1)

使用List集合,例如:

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)的文档:

  

删除指定的元素   此列表中的位置(可选   操作)。随后转移   左边的元素(减去一个   来自他们的指数)。返回   从中移除的元素   列表。

相关问题