Java ArrayList how to add elements at the beginning

后端 未结 14 1440
忘了有多久
忘了有多久 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:24
    import java.util.*:
    public class Logic {
      List<String> list = new ArrayList<String>();
      public static void main(String...args) {
      Scanner input = new Scanner(System.in);
        Logic obj = new Logic();
          for (int i=0;i<=20;i++) {
            String string = input.nextLine();
            obj.myLogic(string);
            obj.printList();
          }
     }
     public void myLogic(String strObj) {
       if (this.list.size()>=10) {
          this.list.remove(this.list.size()-1);
       } else {
         list.add(strObj); 
       }
     }
     public void printList() {
     System.out.print(this.list);
     }
    }
    
    0 讨论(0)
  • 2020-12-02 07:25

    You can take a look at the add(int index, E element):

    Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

    Once you add you can then check the size of the ArrayList and remove the ones at the end.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 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<String> 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.

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

    You can use

    public List<E> addToListStart(List<E> list, E obj){
    list.add(0,obj);
    return (List<E>)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.

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

    Java LinkedList provides both the addFirst(E e) and the push(E e) method that add an element to the front of the list.

    https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#addFirst(E)

    0 讨论(0)
提交回复
热议问题