Elements can be added in the middle of an ArrayList by using the java. util. ArrayList. add() method.
LinkedList. addFirst() method in Java is used to insert a specific element at the beginning of a LinkedList. Parameters: This function accepts a single parameter element as shown in the above syntax. The element specified by this parameter is appended at beginning of the list.
The java. util. ArrayList. add(int index, E elemen) method inserts the specified element E at the specified position in this list.It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).
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);
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)
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"
Space and time complexity of insertion is with LinkedList
constant (O(1)
). See the Big-O cheatsheet.
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.
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 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.
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