assassinsweed1 assassinsweed1 - 5 months ago 45
Java Question

Java Error: "Exception in thread "main" java.lang.IndexOutOfBoundsException:"

I am creating a program where there is an array called "student_id" which contains integers of IDs. I have created a method where you can remove an ID from the array which I have included below. However, when I try to test it, it comes with the following error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 332, Size: 3
at java.util.ArrayList.rangeCheck(
at java.util.ArrayList.remove(
at Module.removeStudent(
at TestModule.main(

What have I done wrong? Thank you.

public boolean removeStudent(int id){
//removes a student from the module
if (id >= 100 && id <= 99999999 && student_id.contains(id)){
return true;
} else {
return false;

System.out.println("Testing removeStudent, the following inputs should return true");
System.out.println("28262722: " + (test1.removeStudent(28262722)));


As shown by your error message, you are attempting to remove the 332nd object in the ArrayList even though there are only three objects.

ArrayList.remove() can be given a parameter of either an object to remove (what you were trying to do, I assume) or an int index. You are trying to pass it an int to get it to remove that int, but it is instead treating the int like an index and trying to remove whatever is at that index.

So, when you call test1.removeStudent(28262722), you are not removing the student with that ID--instead, you are removing the student at the 28262722nd position in the ArrayList (I'm not sure why the error comes up with the index of 332.)

To fix this, you would have to use a different object in your ArrayList (maybe ints disguised as Strings--i.e. "28262722" instead of 28262722), or you would have to remove the student based on the index instead of the id.