jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes ArrayList throws Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ArrayList throws " Watch "ArrayList throws " New topic

ArrayList throws

santoshkumar savadatti
Ranch Hand

Joined: Apr 27, 2010
Posts: 95
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

Joined: Oct 25, 2008
Posts: 2700

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.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
santoshkumar savadatti
Ranch Hand

Joined: Apr 27, 2010
Posts: 95
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:

Have you checked out Aspose?
subject: ArrayList throws
It's not a secret anymore!