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
MyInput : 5
1 2 3 4 5
Please help me out and tell me what i am doing wrong?
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.
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: