[java] Add object to ArrayList at specified index

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<object> list = new ArrayList<object>();

I've got some objects I want to add and each object has to be at a certain position. It is necessary however that they can be added in each possible order. When I try this, it doesn't work and I get an IndexOutOfBoundsException:

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

What I have tried is filling the ArrayList with null and then doing the above. It works, but I think it's a horrible solution. Is there another way to do this?

This question is related to java android arraylist

The answer is


This is a possible solution:

list.add(list.size(), new Object());

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.


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.


If that's the case then why don't you consider using a regular Array, initialize the capacity and put objects at the index you want.

Object[] list = new Object[10];

list[0] = object1;
list[2] = object3;
list[1] = object2;

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)


If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map


You can use Array of objects and convert it to ArrayList-

Object[] array= new Object[10];
array[0]="1";
array[3]= "3";
array[2]="2";
array[7]="7";

List<Object> list= Arrays.asList(array);

ArrayList will be- [1, null, 2, 3, null, null, null, 7, null, null]


You should set instead of add to replace existing value at index.

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

List will contain [object1,object2]


How about this little while loop as a solution?

private ArrayList<Object> list = new ArrayList<Object>();

private void addObject(int i, Object object) {
    while(list.size() < i) {
        list.add(list.size(), null);
    }
    list.add(i, object);
}
....

addObject(1, object1)
addObject(3, object3)
addObject(2, object2)

You need to populate the empty indexes with nulls.

while (arraylist.size() < position)
{
     arraylist.add(null);
}

arraylist.add(position, object);

You could also override ArrayList to insert nulls between your size and the element you want to add.

import java.util.ArrayList;


public class ArrayListAnySize<E> extends ArrayList<E>{
    @Override
    public void add(int index, E element){
        if(index >= 0 && index <= size()){
            super.add(index, element);
            return;
        }
        int insertNulls = index - size();
        for(int i = 0; i < insertNulls; i++){
            super.add(null);
        }
        super.add(element);
    }
}

Then you can add at any point in the ArrayList. For example, this main method:

public static void main(String[] args){
    ArrayListAnySize<String> a = new ArrayListAnySize<>();
    a.add("zero");
    a.add("one");
    a.add("two");
    a.add(5,"five");
    for(int i = 0; i < a.size(); i++){
        System.out.println(i+": "+a.get(i));
    }
}   

yields this result from the console:

0: zero

1: one

2: two

3: null

4: null

5: five


@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

*/

I think the solution from medopal is what you are looking for.

But just another alternative solution is to use a HashMap and use the key (Integer) to store positions.

This way you won't need to populate it with nulls etc initially, just stick the position and the object in the map as you go along. You can write a couple of lines at the end to convert it to a List if you need it that way.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable