There is a canonical answer for ArrayIndexOutOfBoundsException
in Java: What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
An ArrayIndexOutOfBoundsException
is-a IndexOutOfBoundsException
(meaning that it is actually a subclass). The associated tag is indexoutofboundsexception.
However, the current question and answer focus specifically on the ArrayIndexOutOfBoundsException
that is thrown when really using an array. The equally common case where someone writes
for (int i=0; i<=list.size(); i++) { ... }
is not covered there.
Of course, one could argue that this is nearly a syntactical detail, and everybody should be able to recognize the pattern. But one has to assume that exactly the people who ask about an IndexOutOfBoundsException
are absolute beginners. Closing their questions as a duplicate might cause them to respond with something along the lines of "I'm not using an array, so this does not help me!!!111". There are questions about IndexOutOfBoundsException
, and people obviously did not find the matching answer or recognize the pattern (namely, that <=
vs <
is the crucial point here)
Should the current canonical Q/A be generalized to cover ArrayIndexOutOfBoundsException
and IndexOutOfBoundsException
?
(It would have to be done carefully, of course. Trying to squeeze too much information into the Q/A may be confusing. For example, it should try to not mention the exception inheritance hierarchy etc., because that's distracting and not relevant for the people who are asking this sort of question)
The alternative would be to close questions about IndexOutOfBoundsException
as a duplicate, linking to the canonical in its current form, and mentioning (e.g. in a comment) that the fix is the same: "Just change <=
to <
".
(Note: The canonical Q/A for ArrayIndexOutOfBoundsException
has also been discussed in Is this an acceptable canonical question and answer for a common Java exception? , but this did not focus on generalizing it)