Search code examples
javalistloopsindexoutofboundsexception

How to check if index + 1 is present in ArrayList to avoid IndexOutOfBoundsException


A list contains several lists. From these, 2 lists are always checked one after the other and values are subtracted from each other. The results are then saved in a new list.

This is how the code looks like:

    List<List<AccountlinevaluesEntity>> a_l_v_eList = new ArrayList<>();
    List<List<AccountlinevaluesEntity>> finalList = new ArrayList<>();

    //creates multiple ArrayLists in List, based on numbers of monthList
    for (int i = 0; i < monthList.size(); i++) {
        a_l_v_eList.add(new ArrayList<>());
        finalList.add(new ArrayList<>());
    }
    //splits original List and seperates lists
    for (AccountlinevaluesEntity a_l_v_E : alveList) {
        for (int k = 0; k < a_l_v_eList.size(); k++) {
            for (int j = 0; j < monthList.size(); j++) {
                if (j == k) {
                    if (a_l_v_E.getPeriod().equals(String.valueOf(monthList.get(j)))) {
                        a_l_v_eList.get(j).add(a_l_v_E);
                    }
                }
            }
        }
    }

    List<AccountlinevaluesEntity> tempList;

    for (int i = 0; i < a_l_v_eList.size(); i++) {
        List<AccountlinevaluesEntity> firstMonth = a_l_v_eList.get(i);

        tempList = a_l_v_eList.get(i + 1);

        for (int j = 0; j < firstMonth.size(); j++) {
            AccountlinevaluesEntity firstMonthElement = firstMonth.get(j);

            for (AccountlinevaluesEntity nextMonthElementTemp : tempList) {
                if (firstMonthElement.getAccountNumber() == nextMonthElementTemp.getAccountNumber()) {
                    nextMonthElementTemp.setAmount(subtractAmount(firstMonthElement.getAmount(), nextMonthElementTemp.getAmount()));
                    finalList.get(i).add(nextMonthElementTemp);
                    break;
                }
            }
        }
    }

In itself, the code makes first what he should.

But logically at some point, it finally bangs in this line:

tempList = a_l_v_eList.get(i + 1);

Can anyone tell me how to check if index + 1 is present? I am also open for general code improvements.


Solution

  • Change this line

    for (int i = 0; i < a_l_v_eList.size(); i++) {
    

    to

    for (int i = 0; i < a_l_v_eList.size()-1; i++) {
    

    That way you will end the loop once no next element is available.