risdb97
risdb97

Reputation: 11

For Each Loop with ArrayList

In the below code, how is it that in the inner For Each loop, we can create a variable of type int from the variable we created in the outer For Each loop that is of type List? Yet if we try to create this variable of primitive type int, there is an error. Can't work out how we can create a For Each variable of type int from userAge, but not from userAges.

   List <List<Integer>> userAges = new ArrayList<List<Integer>>();

    userAges.add(Arrays.asList(51, 48, 21));
    userAges.add(Arrays.asList(33, 51, 19));
    userAges.add(Arrays.asList(39, 47, 58));

    for (List<Integer> userAge : userAges)
    {
        for (int age : userAge)
        {
            System.out.print(age + " ");
        }
        System.out.println();
    }

Upvotes: 1

Views: 1659

Answers (1)

Bohemian
Bohemian

Reputation: 424983

Java will auto-unbox the primitive wrapper classes to their primitive equivalent, so given

List<Integer> userAge; // what the outer loop provides to the inner loop

We can write either:

for (Integer age : userAge)

or:

for (int age : userAge)

More generally, given:

Integer integer;

We can write:

int i = integer;

Read the full specification here.

Upvotes: 3

Related Questions