Java ArrayList how to add elements at the beginning

后端 未结 14 1533
忘了有多久
忘了有多久 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:28

    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);
    

提交回复
热议问题