且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 ArrayList 中删除多个元素

更新时间:2023-09-26 16:36:40

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

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());