Java ArrayList how to add elements at the beginning

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

    You can use

    public List addToListStart(List list, E obj){
    list.add(0,obj);
    return (List)list;
    
    }
    

    Change E with your datatype

    If deleting the oldest element is necessary then you can add:

    list.remove(list.size()-1); 
    

    before return statement. Otherwise list will add your object at beginning and also retain oldest element.

    This will delete last element in list.

提交回复
热议问题