Java ArrayList how to add elements at the beginning
Solution 1
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);
Solution 2
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.
Solution 3
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.
Solution 4
You may want to look at Deque. it gives you direct access to both the first and last items in the list.
Solution 5
What you are describing, is an appropriate situation to use Queue
.
Since you want to add
new element, and remove
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)
and remove()
which adds at the end the new element, and removes from the beginning the old element, respectively.
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(5);
queue.add(6);
queue.remove(); // Remove 5
So, every time you add an element to the queue
you can back it up with a remove
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
: -
CircularFifoBuffer is a first in first out buffer with a fixed size that replaces its oldest element if full.
Buffer queue = new CircularFifoBuffer(2); // Max size
queue.add(5);
queue.add(6);
queue.add(7); // Automatically removes the first element `5`
As you can see, when the maximum size is reached, then adding new element automatically removes the first element inserted.
Related videos on Youtube
ZeDonDino
Updated on April 30, 2022Comments
-
ZeDonDino about 2 years
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?
-
Vishy over 11 yearsDo you mean like
remove
andadd
? -
Vishy over 11 yearsWhat are you using your
arraylist stack queue whatever
for as adding to the start of an array is best avoided and it sounds like you should be using a different collection. -
Yegoshin Maxim over 11 yearsFirst, you should make something yourself. What have you done so far?
-
-
Guillaume F. over 7 yearsI am surprised you are the only answer talking about Deque, this is obviously the best optimal solution.
-
Samyak Upadhyay almost 7 yearsReversing a list twice. Will it add the run time of the algorithm by a big margin as compared to the above accepted solution?
-
DPM almost 7 yearsI wouldn't touch any apache library with a ten foot pole, especially since guava's collection classes exist. Guava's EvictingQueue might be a good choice here.
-
Patrick almost 7 yearsIt adds 2n, so yes, but if you have list of <50 you wouldnt be able to micro benchmark the difference on most modern machines
-
Admin about 2 yearsAs it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.