Add object to ArrayList at specified index

前端 未结 14 1422
南笙
南笙 2020-11-30 18:59

I think it\'s a fairly simple question, but I can\'t figure out how to do this properly.

I\'ve got an empty arraylist:

ArrayList list =         


        
      
      
      
14条回答
  •  隐瞒了意图╮
    2020-11-30 19:35

    @Maethortje 
    
    The problem here is java creates an empty list when you called new ArrayList and 
    

    while trying to add an element at specified position you got IndexOutOfBound , so the list should have some elements at their position.

    Please try following

    /*
      Add an element to specified index of Java ArrayList Example
      This Java Example shows how to add an element at specified index of java
      ArrayList object using add method.
    */
    
    import java.util.ArrayList;
    
    public class AddElementToSpecifiedIndexArrayListExample {
    
      public static void main(String[] args) {
        //create an ArrayList object
        ArrayList arrayList = new ArrayList();
    
        //Add elements to Arraylist
        arrayList.add("1");
        arrayList.add("2");
        arrayList.add("3");
    
        /*
          To add an element at the specified index of ArrayList use
          void add(int index, Object obj) method.
          This method inserts the specified element at the specified index in the
          ArrayList.  
        */
        arrayList.add(1,"INSERTED ELEMENT");
    
        /*
          Please note that add method DOES NOT overwrites the element previously
          at the specified index in the list. It shifts the elements to right side
          and increasing the list size by 1.
        */
    
        System.out.println("ArrayList contains...");
        //display elements of ArrayList
        for(int index=0; index < arrayList.size(); index++)
          System.out.println(arrayList.get(index));
    
      }
    }
    
    /*
    Output would be
    ArrayList contains...
    1
    INSERTED ELEMENT
    2
    3
    
    */
    

提交回复
热议问题