• 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
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

ArrayList IndexOutOfBoundsException  RSS feed

Posts: 23
  • 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(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
at Test.main(Test.java:15)

MyInput : 5
              1 2 3 4 5

Please help me out and tell me what i am doing wrong?
Posts: 12815
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: 62231
  • 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.
Switching from electric heat to a rocket mass heater reduces your carbon footprint as much as parking 7 cars. Tiny ad:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!