4

我在这里有一个对象的通用数组列表,我想删除某些元素,问题是当我用 for 循环迭代列表时,我不能做一个简单的remove()'s 序列,因为每次删除后元素都会移动。

谢谢

4

6 回答 6

17

使用迭代器删除元素

喜欢

Iterator itr = list.iterator();
String strElement = "";
while (itr.hasNext()) {
    strElement = (String) itr.next();
    if (strElement.equals("2")) {
        itr.remove();
    }
}
于 2012-07-11T09:01:41.767 回答
2

您可以通过这种方式迭代列表...

public void clean(List<Kopek> kopeks) {
  for(Kopek kopek : kopeks) {
    if (kopek.isDirty())
      kopeks.remove(kopek);
  }
}

这相当于...

public void clean1(List<Kopek> kopeks) {
  Iterator<Kopek> kopekIter = kopeks.iterator();

  while (kopekIter.hasNext()) {
    Kopek kopek = kopekIter.next();
    if (kopek.isDirty())
      kopeks.remove(kopek);
  }
}

不要这样做......(由于您已经观察到的原因。)

public void clean(List<Kopek> kopeks) {
  for(int i=0; i<kopeks.size(); i++) {
    Kopek kopek = kopeks.get(i);
    if (kopek.isDirty())
      kopeks.remove(i);
  }
}

但是,我相信按索引而不是按对象删除更有效。按对象删除效率不高,因为列表在大多数情况下不是散列列表。

kopeks.remove(kopek);

对比

kopeks.remove(i);

为了实现位置移除,通过适当地处理移动目标......

public void clean(List<Kopek> kopeks) {
  int i=0;
  while(i<kopeks.size()) {
    Kopek kopek = kopeks.get(i);
    if (kopek.isDirty()) // no need to increment.
      kopeks.remove(i);
    else
      i++;
  }
}
于 2012-07-11T09:28:46.563 回答
1

If you have the objects that you want to remove from your ArrayList<T> you can use :

mArrayList.remove(object);

or you can use an Iterator to remove your objects:

while(iterator.hasNext()){
    if(iterator.next() == some condition for removal){
        iterator.remove();
    }
}
于 2012-07-11T09:05:26.040 回答
1

您可以在遍历ArrayList 时向后迭代并删除。这具有后续元素不需要移动的优点,并且比向前移动更容易编程。

   List<String> arr = new ArrayList<String>();
   ListIterator<String> li = arr.listIterator(arr.size());

    // Iterate in reverse.
    while(li.hasPrevious()) {

        String str=li.previous();
        if(str.equals("A"))
        {
            li.remove();
        }
    }
于 2012-07-11T09:22:53.120 回答
0

不使用迭代器也解决了这个问题。我想做的就是获取要删除的索引并按降序对其进行排序,然后将其从列表中删除。检查下面的代码

Arraylist<obj> addlist = getlist();
List<Integer> indices = new ArrayList<Integer>();
    for(int i=0; i<addlist.size() ;i++){
        if(addlist.get(i).getDelete()){
            indices.add(i);

        }
    }
    Collections.sort(indices, Collections.reverseOrder());
    for (int i : indices)
        addlist.remove(i);
于 2012-07-11T09:40:16.907 回答
0

为要从原始 ArrayList 中删除的数据创建一个单独的 ArrayList,然后通过使用 for 循环对其进行循环来删除这些元素。

ArrayList<Myobj> arr = new ArrayList<Myobj>();

for (Myobj o : arr){

  arr.remove(arr.indexOf(o));

 }
于 2012-07-11T09:05:31.187 回答