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 arra
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.
Take this example :-
List<String> element1 = new ArrayList<>();
element1.add("two");
element1.add("three");
List<String> element2 = new ArrayList<>();
element2.add("one");
element2.addAll(element1);