卸下ArrayList中的多个元素 [英] Remove multiple elements from ArrayList

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

问题描述

我有一大堆的指标,我想这些指标从的ArrayList 删除元素。我不能做一个简单的序列删除(),因为元素也被删除后移秒。我该如何解决这个问题?

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天全站免登陆