Java 如何从指定的索引开始删除数组列表中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18580607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:11:33  来源:igfitidea点击:

How to remove elements in an arraylist start from an indicated index

javaarraylistqueueelement

提问by atom2ueki

As the picture shown, after one time run a method, i want remove the old items, and prepared for next time calculation, but i wondering how to remove elements in an arraylist start from an indicated index, like a queue, obey FIFO algorithm? q1

如图所示,一次运行一个方法后,我想删除旧项目,并为下次计算做准备,但我想知道如何从指定的索引开始删除arraylist中的元素,如队列,遵守FIFO算法? q1

采纳答案by Katona

You can use List#subList(int, int):

您可以使用List#subList(int, int)

List<Integer> list =  ...
list = list.subList(10, list.size()); // creates a new list from the old starting from the 10th element

or, since subListcreates a view on which every modification affects the original list, this may be even better:

或者,由于subList创建了一个视图,每个修改都会影响原始列表,这可能会更好:

List<Integer> list = ...
list.subList(0, 10).clear(); // clears the first 10 elements of list

回答by micha

Just use the remove()method for this.

只需为此使用remove()方法。

Let's assume you want to remove elements with indices from 20 to 30 of an ArrayList:

假设您要删除索引为 an 的 20 到 30 的元素ArrayList

ArrayList<String> list = ...
for (int i = 0; i < 10; i++) { // 30 - 20 = 10
  list.remove(20);
}

Once the first element at index 20is removed element 21moves to index 20. So you have to delete 10 times the element at index 20to remove the next 10 elements.

20删除index 处的第一个元素后,元素21将移动到 index 20。因此,您必须删除 index 处的元素 10 次20才能删除接下来的 10 个元素。

回答by mike

Since you're writing no high performance application it is bad style to store so much semantics in an index variable.

由于您没有编写高性能应用程序,因此在索引变量中存储如此多的语义是一种糟糕的风格。

A better approach would be the use of a map.

更好的方法是使用地图。

E. g. Map<Item, Integer> itemStockand Map<Item, Double> prices. You then also wouldn't have any problems with the remove operation.

例如 Map<Item, Integer> itemStockMap<Item, Double> prices。然后,您在删除操作时也不会有任何问题。