A
A
Andrey Kulagin2020-04-24 20:59:10
Java
Andrey Kulagin, 2020-04-24 20:59:10

How does a double for loop work?

Each element of the two-dimensional array array is sequentially assigned the elements of the one-dimensional array row, in which all elements are sequentially assigned to the cell variable. It is not clear how this works, in the inner for everything is written in a row, but why then the outer for?

public List<Integer> toList(int[][] array) {
  List<Integer> list = new ArrayList<>();
        for (int[] row : array) {
            for (int cell : row) {
                list.add(cell);
            }
        }
    return list;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cheypnow, 2020-04-24
@andrew_1985

The outer forone is needed in order to go through all the arrays inside array.
That is, at the first iteration of the outer loop, listall elements from the first array will be added, at the second iteration from the second, and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question