I am having trouble with an ArrayList, which sould fill a TableModel.
In the 2nd for-loop the app crashes the 3rd time with an
java.lang.IndexOutOfBoundsException: Index: 14, Size: 14
at
if (al.get(i + 4)!=null)
and I dont know why, because i in this case is 10, so it checks for index 14, which actually is null. It should enter the else-loop, but instead it crashes. Thanks for your help, here the code:
String[] teile = tabelleninhalt.split("#");
ArrayList<String> al = new ArrayList<String>();
for (int i = 1; i < teile.length; i++) {
al.add(teile[i]);
}
for (int i = 0; i < al.size(); i = i + 5) {
if (al.get(i + 4)!=null) {
tabModel.addRow(new Object[] { al.get(i), al.get(i + 1),
al.get(i + 2), al.get(i + 3), al.get(i + 4) });
} else {
tabModel.addRow(new Object[] { al.get(i), al.get(i + 1),
al.get(i + 2), al.get(i + 3) });
}
}
No, when the size is 14, there is no index 14. The valid indexes are 0 to 13 inclusive.
Your loop should look like this:
If your list is meant to have batches of 5 entries though, it sounds like you’ve got a problem if you’ve got a size of 14. Shouldn’t the size always be a multiple of 5?
EDIT: If you want to treat a missing final value as effectively null, but still require the previous 4 fields, you may want:
(But it’s hard to tell based on a question which doesn’t give any requirements.)