-1

My code of adding elements through ArrayList :


public class ArrayList2 {
//Delete all ArrayList using Collection remove method
    public static void main(String[] args) throws IndexOutOfBoundsException{


ArrayList<Integer> list = new ArrayList<Integer>();
/*list.add(10);
list.add(20);*/
list.add(30);//Addition using add(int index,Object element) method
list.add(40);
list.add(50);
list.add(4,60);
list.add(70);
list.add(80);
System.out.println("Size of list "+ list.size());
System.out.println("Initial list "+ list);
    }
}

I tried to use Collections add method add(Object) and Lists add method add(Int index, Object o) to add elements.But when I use the above code error is thrown

ldz
  • 2,172
  • 14
  • 20

1 Answers1

0

You're using public void add(int index, E element) of ArrayList when you do list.add(4,60). As the list contains three elements (30, 40, 50), you're trying to add an element to index 4 which does not exist.

From the docs:

/**
 * 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).
 * 
 * @param index index at which the specified element is to be inserted
 * @param element element to be inserted
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */

Probably you want to remove the index and just add 60 to the list via public boolean add(E e).

ldz
  • 2,172
  • 14
  • 20