Java ArrayList how to add elements at the beginning

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

    I think the implement should be easy, but considering about the efficiency, you should use LinkedList but not ArrayList as the container. You can refer to the following code:

    import java.util.LinkedList;
    import java.util.List;
    
    public class DataContainer {
    
        private List list;
    
        int length = 10;
        public void addDataToArrayList(int data){
            list.add(0, data);
            if(list.size()>10){
                list.remove(length);
            }
        }
    
        public static void main(String[] args) {
            DataContainer comp = new DataContainer();
            comp.list = new LinkedList();
    
            int cycleCount = 100000000;
    
            for(int i = 0; i < cycleCount; i ++){
                comp.addDataToArrayList(i);
            }
        }
    }
    

提交回复
热议问题