First example
int windowStart = 0;
for (int i = 0; i + windowSize < fileArray.size(); i++) {
ArrayList <Character> window = new ArrayList <Character> ();
for (int s = windowStart; s <= windowStart + windowSize; s++) {
window.add(fileArray.get(s));
}
windowStart++;
}
VS.
second example
int ind = 0;
for (int i = 0; i + windowSize < fileArray.size(); i++) {
for (int b = ind; b <= windowSize + ind; b++) {
window.add(fileArray.get(b));
}
ind++;
}
The first one throws an java.lang.IndexOutOfBoundsException while the second one does not and works just fine. fileArray is the same for both, but for 2. the window array is defined as an attribute, while for the first one, the “window” array is defined inside the method (and the for loop). Does that make a difference?
You can’t get an
IndexOutOfBoundsExceptionfor adding a value to a list. The problem is that a value ofsis equal or greater then the actual size of thefileArrayarray or list.And because the loops in both examples are equivalent, the problem should be found outside the lines of code you’ve just posted.
Try to debug (break on
IndexOutOfBoundsExceptionif you are using an IDE, otherwise add some simpleSystem.out.printlnstatements to find out, whysis greater than expected.