In the below code I’m getting the following error :
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
The size is 1 for copiedppList.size()
for (int domainData = 0; domainData < copiedppList.size(); domainData++) {
if (domainData == 0) {
firstValue.setNewValue(firstValue.getFieldValue());
DomainItemFieldHistory oldValue = copiedppList.get(domainData + 1);
if (firstValue.getFieldID().equals(oldValue.getFieldID())) {
firstValue.setOldValue(oldValue.getFieldValue());
}
}
}
The below line is causing the mentioned issue:
DomainItemFieldHistory oldValue = copiedppList.get(domainData + 1);
How can i avoid this?
What condition can be added to prevent the error?
Changing the terminating condition to
copiedppList.size() - 1will prevent the out of bounds exception.Array indexes are zero based, so the last valid index is
size() - 1. The posted code can iterate tosize() - 1but makes the following call:causing the exception.
If the loop must iterate over all elements then you need to protect the
+ 1call. For example: