160

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 In which I want to add object 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?

6
  • 7
    You get an IndexOutOfBoundsException because the list is empty and you cannot access a list position that doesn't exist...
    – Vic
    Sep 12, 2011 at 8:10
  • 1
    Is there a way to create that position without filling the list with null objects? To me it seems like it's a really weird solution.
    – J. Maes
    Sep 12, 2011 at 8:16
  • 1
    I don't think so... If you need to add the objects in a random order, you would have to look for another way of doing it.. For example with a typical array: 'Object[]' and then you shouldn't have to fill it, just initialize
    – Vic
    Sep 12, 2011 at 8:20
  • 1
    @Maethortje it is not really a weird problem. Look up sparse lists, reference.wolfram.com/mathematica/tutorial/… seems a good article. In Java though, a Map with index as key might be the easiest approach. Sep 12, 2011 at 8:27
  • 2
    @Pan Even if you declare the size.. It just does not initialize the list, but declare how many space you want to reserve in memory.. As I see it, a list is an array of elements which also has a pointer to the next element. If you try to add an element into the third position when you have the second empty (or null) you have no pointer to help you know it is the third element..: 1->2->3 is OK, but 1->*->3 here you have a problem...
    – Vic
    Feb 4, 2013 at 8:36

14 Answers 14

234

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.

3
  • 3
    A hashmap would indeed be able to solve this problem. I think I'll go for that one since it doesn't seem like I can add something at location 3 when there is no object at location 2.
    – J. Maes
    Sep 12, 2011 at 8:35
  • short but most Answer. Others are just on wrong track Apr 22, 2015 at 7:36
  • A constructive logic!
    – Arsal Imam
    Nov 18, 2018 at 22:23
37

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]

1
  • 3
    One drawback is you have to know size in advance. Dec 20, 2017 at 12:26
17

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;
7
  • You initalize the capacity, but not the size of the 'ArrayList'. The size is defined as number of elements, and when the index is > size the exception comes...
    – Vic
    Sep 12, 2011 at 8:11
  • @Vic, I misread the question at first, but thanks for the tip.
    – mohdajami
    Sep 12, 2011 at 8:12
  • I initialized the capacity at 10, but I still get an IndexOutOfBoundsExceptopn when adding an object. Same with changing the capacity with ensureCapacity. Only thing that works is filling with null at the moment...
    – J. Maes
    Sep 12, 2011 at 8:14
  • @Maethortje Look for the difference between "size" and "capacity"... The exception comes when the index is > the size, not when it is > capacity.....
    – Vic
    Sep 12, 2011 at 8:15
  • As the guys mentioned, you are adding an object at index 3, while the size of the list is still 1. That's not possible. Adding at specific index is allowed as long as this index is inside the boundaries of the list, for example if your list has 3 objects, you cannot add an object at index 100.
    – mohdajami
    Sep 12, 2011 at 8:17
15

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

1
  • 1
    Attention! If you put at the end a.add(3, "three");, the fifth element will be pushed forward. You will have: "6: five" Oct 8, 2021 at 23:48
11

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)

3
  • You are right @Hemal, @Maethortje Why dont you check the size of the list before you add the element to the list ? check if the position you are trying to add is less than the size of the list, if not then you can just do a normal list.add("element");
    – Rakesh
    Sep 12, 2011 at 8:22
  • 2
    As i understand it, the "problem" is to add the element at position 3 even if there is not an element in position 2...
    – Vic
    Sep 12, 2011 at 8:27
  • @Vis that is a sparse list -- see my comment to the question. Sep 12, 2011 at 8:28
5

You need to populate the empty indexes with nulls.

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

arraylist.add(position, object);
3
@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

*/
3
  • I understand the problem which causes my error. It seems like I have to add objects to the subsequent positions before I can add an object to that position. The moment I'm adding, I'm not disposing of all the objects I want to add. Do you think adding null objects is a proper solution then?
    – J. Maes
    Sep 12, 2011 at 8:23
  • @Maethortje It wont be very fair to do this, as its just a hack :)
    – Sankalp
    Sep 12, 2011 at 8:38
  • you need to remove the code sample quotes from the first paragraph. Nov 19, 2013 at 16:09
2

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)
2

This is a possible solution:

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

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.

1
  • Isn't TreeMap is better since ordered by keys? Dec 20, 2017 at 12:28
1

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.

1

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]

1

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.

1
  • 2
    i'm just passing by when i notified your answer... actually, index must be lower or equal than the real length of the list at the moment we are inserting new item. exhample: list size is 2: adding in index 2 will work. adding in index 3 will throw an exception. (It was tested) Nov 17, 2019 at 21:50
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.