Add object to ArrayList at specified index

前端 未结 14 1345
南笙
南笙 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
    
    */
    
    0 讨论(0)
  • 2020-11-30 19:40

    You can do it like this:

    list.add(1, object1)
    list.add(2, object3)
    list.add(2, object2)
    

    After you add object2 to position 2, it will move object3 to position 3.

    If you want object3 to be at position3 all the time I'd suggest you use a HashMap with position as key and object as a value.

    0 讨论(0)
  • 2020-11-30 19:46

    I draw your attention to the ArrayList.add documentation, which says it throws IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

    Check the size() of your list before you call list.add(1, object1)

    0 讨论(0)
  • 2020-11-30 19:46

    You need to populate the empty indexes with nulls.

    while (arraylist.size() < position)
    {
         arraylist.add(null);
    }
    
    arraylist.add(position, object);
    
    0 讨论(0)
  • 2020-11-30 19:47

    Suppose you want to add an item at a position, then the list size must be more than the position.

    add(2, item): this syntax means, move the old item at position 2 to next index and add the item at 2nd position.

    If there is no item in 2nd position, then this will not work, It'll throw an exception.

    That means if you want to add something in position 2,

    your list size must be at least (2 + 1) =3, so the items are available at 0,1,2 Position.

    in that way it is ensured that the position 2 is accessed safely and there would be no exception.

    0 讨论(0)
  • 2020-11-30 19:48

    Bit late but hopefully can still be useful to someone.

    2 steps to adding items to a specific position in an ArrayList

    1. add null items to a specific index in an ArrayList
    2. Then set the positions as and when required.

          list = new ArrayList();//Initialise the ArrayList
      for (Integer i = 0; i < mItems.size(); i++) {
          list.add(i, null); //"Add" all positions to null
      }
         // "Set" Items
          list.set(position, SomeObject);
      

    This way you don't have redundant items in the ArrayList i.e. if you were to add items such as,

    list = new ArrayList(mItems.size());    
    list.add(position, SomeObject);
    

    This would not overwrite existing items in the position merely, shifting existing ones to the right by one - so you have an ArrayList with twice as many indicies.

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