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?
You can take a look at the add(int index, E element):
Once you add you can then check the size of the ArrayList and remove the ones at the end.
What you are describing, is an appropriate situation to use
Queue
.Since you want to
add
new element, andremove
the old one. You can add at the end, and remove from the beginning. That will not make much of a difference.Queue has methods
add(e)
andremove()
which adds at the end the new element, and removes from the beginning the old element, respectively.So, every time you add an element to the
queue
you can back it up with aremove
method call.UPDATE: -
And if you want to fix the size of the
Queue
, then you can take a look at: -ApacheCommons#CircularFifoBuffer
From the
documentation
: -As you can see, when the maximum size is reached, then adding new element automatically removes the first element inserted.
I had a similar problem, trying to add an element at the beginning of an existing array, shift the existing elements to the right and discard the oldest one (array[length-1]). My solution might not be very performant but it works for my purposes.
Good luck
Using Specific Datastructures
There are various data structures which are optimized for adding elements at the first index. Mind though, that if you convert your collection to one of these, the conversation will probably need a time and space complexity of
O(n)
Deque
The JDK includes the
Deque
structure which offers methods likeaddFirst(e)
andofferFirst(e)
Analysis
Space and time complexity of insertion is with
LinkedList
constant (O(1)
). See the Big-O cheatsheet.Reversing the List
A very easy but inefficient method is to use reverse:
If you use Java 8 streams, this answer might interest you.
Analysis
O(n)
O(1)
Looking at the JDK implementation this has a
O(n)
time complexity so only suitable for very small lists.you can use this code
You may want to look at Deque. it gives you direct access to both the first and last items in the list.