Ryan Stull
Ryan Stull

Reputation: 1096

Different looping behaviors in Groovy

Why do these two loops have different results? I thought they would both initialize all of the values in each array to 5 but only the second one works. Could someone explain why this is?

static main(args)
{
    double[][] x = new double[3][3]
    double[][] y = new double[3][3]

    for(row in x)
    {
        for(num in row)
        {
            num=5
        }
    }

    for(int i=0;i<y.size();i++)
    {
        for(int j=0;j<y[i].size();j++)
        {
            y[i][j]=5
        }
    }

    println "x: ${x}" 
    println "y: ${y}"
}

And here's the output

x: [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
y: [[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]

Upvotes: 2

Views: 150

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96385

In the first loop you're changing a local variable that never updates what is in the array. num holds a copy of the data in the array element, but there's no reference back to the array entry, so changing it has no effect on the array.

This way is a little groovier than the old-style for-loop:

for (i in 0..x.length - 1) {
    for (j in 0..y.length - 1) {
        x[i][j] = 5
    }
}

or you can do without the for:

(i in 0 .. x.length - 1).each { i ->
    (j in 0 .. y.length - 1).each { j ->
        x[i][j] = 5
    }
}

Upvotes: 2

Grzegorz Żur
Grzegorz Żur

Reputation: 49161

First pair of for loops does nothing and it is correct. num is a new variable in scope of inner for. It is a reference to the integer from table. When you assign it, it becomes a reference to value 5. Table cell does not change.

For a C programmer.

int five = 5;
int *num;

It is:

num = &five;

It is not:

*num = five; 

Upvotes: 1

Related Questions