Win a copy of Python Continuous Integration and Delivery this week in the Python forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

ArrayList IndexOutOfBoundsException  RSS feed

Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I write a program to add only even no in ArrayList but the  program gives runtime Exception as :

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(
at java.util.ArrayList.get(
at Test.main(

MyInput : 5
              1 2 3 4 5

Please help me out and tell me what i am doing wrong?
Posts: 13155
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Examine the error message carefully. If the size of the ArrayList is 2, then what is the largest valid index? Remember, indices for an ArrayList are 0-based. What is the index you are trying to use? Is that a valid index value? The main problem you should address is on line 15 and line 17. You are using i which goes from 0 to 4. However, if line 17 succeeds in removing an element, that changes the size of the list. Walk through your code manually and track the value of i, the size of the list, and the valid values that you can pass to get() and remove() versus the actual value you're passing.
Posts: 63391
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably not the actual cause of the problem, but there is a overloading issue there. For every other type of input, it is cast to Object, which means all primitives would be boxed, and the [first] element equal to that object is removed. But not for ints, because that defaults to being the index where an element is removed. See remove() in the methods of the List interface. If you call myList.remove(123);, the 123 is NOT boxed to an Integer.
Well behaved women rarely make history - Eleanor Roosevelt. tiny ad:
Become a Java guru with IntelliJ IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!