Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 990
atom2ueki Avatar asked Sep 02 '13 20:09

atom2ueki


People also ask

How do you remove an element from a particular index in ArrayList?

ArrayList. remove(int index) method removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).

How do you remove the first index of an ArrayList in Java?

We can use the remove() method of ArrayList container in Java to remove the first element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the first element's index to the remove() method to delete the first element.


1 Answers

You can use 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 subList creates a view on which every modification affects the original list, this may be even better:

List<Integer> list = ...
list.subList(0, 10).clear(); // clears the first 10 elements of list
like image 165
Katona Avatar answered Nov 11 '22 12:11

Katona