How to remove items in arraylist start at the specified index

As shown in the figure, after a single run of the method, I want to delete the old elements and get ready for calculation the next time, but I wonder how to remove the elements at the beginning of the arraylist from the specified index, for example, in turn, obey the FIFO algorithm? q1

+6
source share
3 answers

You can use the SubList of the list (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 subList creates a view by which each modification affects the original list, this could be even better:

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

Just use remove () to do this.

Suppose you want to remove items with indices from 20 to 30 from an ArrayList :

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

After removing the first element in index 20 element 21 moves to index 20 . Therefore, you must remove 10 times the item in index 20 to remove the next 10 items.

+1
source

Since you are not writing a high-performance application, it is a bad style to store so much semantics in an index variable.

A better approach would be to use a map.

E. G. Map<Item, Integer> itemStock and Map<Item, Double> prices . You will also not have problems with the delete operation.

0
source

Source: https://habr.com/ru/post/953008/


All Articles