I need to get the last three elements added to a List. Are there any utility methods for this or will I just use a for loop that iterates down from "size(myList) - 1"?
We can use the remove() method of ArrayList container in Java to remove the last element. ArrayList provides two overloaded remove() method: remove(int index) : Accept index of the object to be removed. We can pass the last elements index to the remove() method to delete the last element.
Approach: Get the ArrayList with elements. Get the first element of ArrayList with use of get(index) method by passing index = 0. Get the last element of ArrayList with use of get(index) method by passing index = size – 1.
The lastIndexOf() method of ArrayList in Java is used to get the index of the last occurrence of an element in an ArrayList object. Parameter : The element whose last index is to be returned. Returns : It returns the last occurrence of the element passed in the parameter.
Arraylist will hold the last element added at the end of the list. So it keeps the order of insertion. But it's a random access container, it doesn't really have a sense of first in first out. As a side note, just based on the way that ArrayList works internally, it wouldn't be a good idea to use it as a FIFO queue.
You could use List.subList()
to get a view onto the tail of the original list:
List<E> tail = l.subList(Math.max(l.size() - 3, 0), l.size());
Here, Math.max()
takes care of the case when l
contains fewer than three elements.
See:
List.subList(arg0, arg1)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With