• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ArrayList throws

 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic