Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ArrayList giving unordered output?

Tags:

java

loops

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?

like image 766
Amrut Dange Avatar asked Aug 28 '13 12:08

Amrut Dange


1 Answers

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
like image 114
Bort Avatar answered Oct 05 '22 18:10

Bort