java - Why ArrayList giving unordered output? -


i have written java program, add integer in arraylist , remove integer arraylist . not giving me proper result. here 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 follows

    removed elements=>6 removed elements=>8 exception in thread "main" java.lang.indexoutofboundsexception: index: 2, size: 2     @ java.util.arraylist.rangecheck(arraylist.java:547)     @ java.util.arraylist.remove(arraylist.java:387)     @ collectiontemp.main(collectiontemp.java:19) 

why getting output this?

your array:

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

then remove @ 1, , increments 2:

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

remember array indexes start @ 0, last element @ a.length - 1

you exception because loop condition i <= a.size(), @ final iteration:

a[0] = 7 a[1] = 9   2  <-- 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -