Java ArrayList how to add elements at the beginning

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

    Using Specific Datastructures

    There are various data structures which are optimized for adding elements at the first index. Mind though, that if you convert your collection to one of these, the conversation will probably need a time and space complexity of O(n)

    Deque

    The JDK includes the Deque structure which offers methods like addFirst(e) and offerFirst(e)

    Deque deque = new LinkedList<>();
    deque.add("two");
    deque.add("one");
    deque.addFirst("three");
    //prints "three", "two", "one"
    

    Analysis

    Space and time complexity of insertion is with LinkedList constant (O(1)). See the Big-O cheatsheet.

    Reversing the List

    A very easy but inefficient method is to use reverse:

     Collections.reverse(list);
     list.add(elementForTop);
     Collections.reverse(list);
    

    If you use Java 8 streams, this answer might interest you.

    Analysis

    • Time Complexity: O(n)
    • Space Complexity: O(1)

    Looking at the JDK implementation this has a O(n) time complexity so only suitable for very small lists.

提交回复
热议问题