11

I have written java program, to add integer in ArrayList and remove that integer from ArrayList . but it not giving me proper result. here is my code..

public static void main(String args[])
  {
    ArrayList<Integer> a=new ArrayList<Integer>();

    a.add(6);
    a.add(7);
    a.add(8);
    a.add(9);

    for(int i=0;i<=a.size();i++)
    {

        System.out.println("Removed Elements=>"+a.remove(i));
    }
  }

it giving me output as follows

    Removed Elements=>6
Removed Elements=>8
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.remove(ArrayList.java:387)
    at CollectionTemp.main(CollectionTemp.java:19)

why i am getting output like this?

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
Amrut Dange
  • 191
  • 1
  • 6

13 Answers13

49

Your array:

a[0]=6
a[1]=7 <-- i
a[2]=8
a[3]=9

Then you remove at 1, and i increments to 2:

a[0]=6
a[1]=8
a[2]=9 <-- i

Remember that array indexes start at 0, so the last element is at a.length - 1

You get your exception because the loop condition i <= a.size(), so at the final iteration:

a[0] = 7
a[1] = 9
  2  <-- i
hyde
  • 60,639
  • 21
  • 115
  • 176
Bort
  • 7,398
  • 3
  • 33
  • 48
19

When you remove items from a list, or any collection, you either use the iterator, or you use a reverse loop like this.

for (int i = (a.size() - 1); i >= 0; i--) {
    System.out.println("Removed Elements=>" + a.remove(i));
}

By going backwards, you avoid the incrementing by 2 problem that has been documented in the other answers.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
9

for first iteration, a.remove(i) causes the element 7 to be removed which is returned by remove method.

For second iteration, the size of list is 3 and you are removing the element at index 2 which is 9. SO remove method returns 9.

In short

Iteration | Size of list | index being removed | element removed
----------+--------------+---------------------+----------------
    1     |      4       |          1          |       7   
    2     |      3       |          2          |       9  
Maroun
  • 94,125
  • 30
  • 188
  • 241
Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
9

If you want a forward loop to remove all elements you could use the following code:

while(!a.isEmpty())
{
    System.out.println("Removed Elements=>" + a.remove(0));
}
tom
  • 2,735
  • 21
  • 35
4

Your problem is that, as you remove elements, you resize the ArrayList. However, your loop counter is not updated, so you iterate past the bounds of the ArrayList.

ArrayList.remove(index) removes the element from the array, not just the contents of the ArrayList, but it actually resizes your ArrayList as you remove items.

First you remove the 1st element of the ArrayList.

Removed Elements=>6

Here the list has been resized from size 4 to size three. Now the element at index 0 is 7.

Next, you step to the element at index 1. This is the number 8.

Removed Elements=>8

Here the ArrayList has been resized to length 2. So there are only elements at index 0 and 1.

Next you step to index 2.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.RangeCheck(ArrayList.java:547)
    at java.util.ArrayList.remove(ArrayList.java:387)
    at CollectionTemp.main(CollectionTemp.java:19)

There is no index 2, so you get an IndexOutOfBoundsException.

codethulhu
  • 3,976
  • 2
  • 21
  • 15
0

the index starts with 0 and ends with size - 1

your loop goes from 1 to size - 2

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
0

ArrayList indexes start at zero, but your loop starts removing at 1. After adding the elements your arraylist looks like this:

0 - 6
1 - 7
2 - 8
3 - 9

Because your loop starts counting at 1, you will first remove the element labeled 1, which is 7. The list will then look like this:

0 - 6
1 - 8
2 - 9

Then the loop will remove the element labeled 2, which is now 9.

So the two mistakes are starting at 1 instead of 0, and incrementing the counter after something has been removed (all elements after the removed element will shift down).

rmhartog
  • 2,293
  • 12
  • 19
0

In the first iteration , i starts from 1, so your second element is removed ie. 7. Now list has

6
8
9

Next iteration is 2, so third element 9 is removed.

Malwaregeek
  • 2,274
  • 3
  • 15
  • 18
0

This is simple logic:

First Iteration i=1:

a[0]=6,
a[1]=7,
a[2]=8;
a[3]=9;

Remove a[i] i.e a[1] removes 7

Second Iteration i=2:

a[0]=6
a[1]=7
a[2]=9

Remove a[i] removes 9

adarshr
  • 61,315
  • 23
  • 138
  • 167
Nargis
  • 4,687
  • 1
  • 28
  • 45
0

Your output is correct : Here is the explaination.

When the loop is executed for the first time, value of i will be 1. and it execute the statement a.remove(1). after removing the value 7 which is at place a[1], '8will be ata[1]'s place. After that i is incremented and becomes 2 and it removes the element a[2] which is 9.

Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
0

The value of i in the loop goes through the following values

0 1 2 3 4

The array has index with values 0 , 1 , 2 , 3

The loop will run for values 0,1,2,3,4

The array is not displayed ordered bcoz when one value is removed the next value is available at index 0

At i=2 , the size of array is 2 and max index is 1 , and hence IndexOutofBound exception is encountered

use the following loop :

    while(a.size()>0)
    {
     System.out.println("Removed Elements=>"+a.remove(0));
    } 
rahul.ramanujam
  • 5,608
  • 7
  • 34
  • 56
0

whenever you remove an element from arraylist it deletes element at specified location.and this should be noted each time the size of arraylist decreases.

Amit Saxena
  • 596
  • 7
  • 18
0

I dont understand what are you trying to remove. If you wan to clear list just call clear() method. If you are trying to remove objects contained in list, than you should know that ArrayList contains objects, not primitive ints. When you add them your are doing the following:

a.add(Integer.valueOf(6));

And there are two remove methods in ArrayList:

remove(Object o) //Removes the first occurrence of the specified element from this list

and the one you are calling:

remove(int index) //Removes the element at the specified position in this list

May be you should call first one:

 a.remove(Integer.valueOf(i));
Mikhail
  • 4,175
  • 15
  • 31