Java ArrayList how to add elements at the beginning
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?
List
has the method add(int, E)
, so you can use:
list.add(0, yourObject);
Afterwards you can delete the last element with:
if(list.size() > 10)
list.remove(list.size() - 1);
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
:
CircularFifoQueue
is a first-in first-out queue with a fixed size that replaces its oldest element if full.
Just initialize it with you maximum size:
CircularFifoQueue queue = new CircularFifoQueue(10);
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 like addFirst(e)
and offerFirst(e)
Deque<String> deque = new LinkedList<>();
deque.add("two");
deque.add("one");
deque.addFirst("three");
//prints "three", "two", "one"
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:
Collections.reverse(list);
list.add(elementForTop);
Collections.reverse(list);
If you use Java 8 streams, this answer might interest you.
Analysis
- Time Complexity:
O(n)
- Space Complexity:
O(1)
Looking at the JDK implementation this has a O(n)
time complexity so only suitable for very small lists.
You can take a look at the add(int index, E element):
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Once you add you can then check the size of the ArrayList and remove the ones at the end.
You may want to look at Deque. it gives you direct access to both the first and last items in the list.