I am trying to remove an object from an ArrayList, but I keep getting an IndexOutOfBounds Error. Now there is plenty information available why this happens when iterating over the ArrayList while removing, however I'm not doing that.
Example:
ArrayList<Character> a = new ArrayList<Character>();
a.add('A');
a.add('B');
a.add('C');
System.out.println(a);
a.remove('A');
System.out.println(a);
prints [A, B, C]
and then fails with:
java.lang.IndexOutOfBoundsException: Index: 65, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.remove(ArrayList.java:474)
at b.<init>(b.java:23)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at bluej.runtime.ExecServer$3.run(ExecServer.java:746)
Why is this happening?
EDIT to clarify this question is not a duplicate of this question:
The specific problem that is occuring here has nothing to do with the usual problems when removing elements while iterating. It is rather caused by the overloaded ArrayList remove
method and the automatic type conversion from char
to int
by java.
This aspect is not covered in the answer of the other question.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…