Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList throws

 
santoshkumar savadatti
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.
I am still a greenhorn.I wrote the following program:



As far as i can see, there's no problem (but then I'm greenhorn )
But when i run the code, it displays numbers at each position as expected.But it also displays the following message:


Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 8, Size: 8
at java.util.ArrayList.RangeCheck(ArrayList.java:546)
at java.util.ArrayList.get(ArrayList.java:321)


and its displayed for different index every time.Sometimes for Index 4 and sometimes for Index 8.
at org.testSample3.example.ListClass.main(ListClass.java:28)
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The for-each loop will iterate through the values of your list and assign the value to i.
So i get's the values of the elements in your list. Then you try to get the element of the
list at the index of i. And since your list contains a bigger value then the list size it
throws an IndexOutOfBoundsException because you're trying to acces element number 9
when there are only 8 elements.
 
santoshkumar savadatti
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You very much wouter.
I actually thought i does not contain the value at that iteration but the "index" for that iteration.
Thnks again.I modified the program and now it runs perfectly
Just used a different variable int pos =0 and for-each loop required just a small modification:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic