Java ArrayList how to add elements at the beginning

后端 未结 14 1441
忘了有多久
忘了有多久 2020-12-02 06:49

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

相关标签:
14条回答
  • 2020-12-02 07:33

    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.

    0 讨论(0)
  • 2020-12-02 07:33

    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);
    
    0 讨论(0)
提交回复
热议问题