I need to add elements to an ArrayList
queue whatever, but when I call the function to add an element, I want it to add the element at the beginning of the array (so it has the lowest index) and if the array has 10 elements adding a new results in deleting the oldest element (the one with the highest index).
Does anyone have any suggestions?
I think the implement should be easy, but considering about the efficiency, you should use LinkedList but not ArrayList as the container. You can refer to the following code:
Java LinkedList provides both the addFirst(E e) and the push(E e) method that add an element to the front of the list.
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#addFirst(E)
You can use
Change E with your datatype
If deleting the oldest element is necessary then you can add:
before return statement. Otherwise list will add your object at beginning and also retain oldest element.
This will delete last element in list.
You can use list methods, remove and add
List
has the methodadd(int, E)
, so you can use:Afterwards you can delete the last element with:
However, you might want to rethink your requirements or use a different data structure, like a
Queue
EDIT
Maybe have a look at Apache's
CircularFifoQueue
:Just initialize it with you maximum size: