Search code examples
javaarraysarraylistapache-commons

When iterating a list of lists, why does calling List.clear on the iterator remove the list from the parent list?


Why does calling clear on the iterator here shorten the size of the batches array?

ArrayList<String> numbers = new ArrayList<>(Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"));
    List<List<String>> numberBatches = ListUtils.partition(numbers, 2);
    for(List<String> numberBatch : numberBatches) {
        for(String number : numberBatch) {
            System.out.println(number);
        }
        numberBatch.clear();
    }

Output

1
2
5
6
9
10

Solution

  • ListUtils.partition(numbers, 2) gives you view of the original list. The List<List<T>> is constructed using the method List#subList(fromIndex, toIndex). This method returns a view of the original list.

    Calling clear on a subList will remove the items from the original, underlying list.

    So when the loop starts the next iteration, it will continue at the index where it left off. But the values at this index have shifted already. That's why you see missing numbers in your sequence.

    It is generally discouraged to modify the collection which you are iterating.