从 ArrayList 中删除多个元素 [英] Remove multiple elements from ArrayList

查看:37
本文介绍了从 ArrayList 中删除多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆索引,我想从 ArrayList 中删除这些索引处的元素.我不能做一个简单的 remove() 序列,因为每次删除后元素都会移动.我该如何解决这个问题?

I have a bunch of indexes and I want to remove elements at these indexes from an ArrayList. I can't do a simple sequence of remove()s because the elements are shifted after each removal. How do I solve this?

推荐答案

按降序对索引进行排序,然后一一删除.如果您这样做,则删除不会影响您以后要删除的任何索引.

Sort the indices in descending order and then remove them one by one. If you do that, there's no way a remove will affect any indices that you later want to remove.

如何对它们进行排序取决于您用来存储索引的集合.如果它是一个列表,你可以这样做:

How you sort them will depend on the collection you are using to store the indices. If it's a list, you can do this:

List<Integer> indices;
Collections.sort(indices, new Comparator<Integer>() {
   public int compare(Integer a, Integer b) {
      //todo: handle null
      return b.compareTo(a);
   }
}

编辑

@aioobe 找到了我没找到的帮手.您可以使用

Edit

@aioobe found the helper that I failed to find. Instead of the above, you can use

Collections.sort(indices, Collections.reverseOrder());

这篇关于从 ArrayList 中删除多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆