Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array loop behaviour

Tags:

java

arrays

loops

I have been testing some different ways to multiply array items with a constant.

I have produced different results depending on how I loop through the array and I'm having trouble understanding this (I'm fairly new to Java and still getting my head around how things are passed or referenced).

Test 1

int[] array = {1, 2, 3, 4};

for (int number : array)
{
    number *= 2;
}

Resulting in array items unmodified:

{1, 2, 3, 4}

It seems like number is not the actual array item, but a new int that is initialised with it's value. Is that correct?


Test 2

I thought that by using an array of Objects might work, assuming number is then a reference to the actual array item. Here is my test of that using Integer instead of int:

Integer[] array = {1, 2, 3, 4};

for (Integer number : array)
{
    number *= 2;
}

Again, resulting in array items unmodified:

{1, 2, 3, 4}

Test 3

After some head scratching I tried a different loop method, like this:

int[] array = {1, 2, 3, 4};

for (int i = 0; i < array.length; i ++)
{
    array[i] *= 2;
}

Resulting in array items multiplied:

{2, 4, 6, 8}

This final result makes sense to me, but I don't understand the results from the second test (or first for that matter). Until now, I've always assumed the loop used in test 1 and 2 was just a shorthand version of the loop used in test 3, but they are clearly different.

Why isn't this working as I expected? Why are these loops different?

like image 986
Darian Avatar asked Sep 05 '14 03:09

Darian


1 Answers

This is because enhanced for loop uses a copy of the value in the array. The code in

for (int number : array) {
    number *= 2;
}

Is similar to:

for(int i = 0; i < array.length; i++) {
    int number = array[i];
    number *= 2;
}

Same happens when using Integer[].

Also, when you use enhanced for loop in an Iterable e.g. List, it uses an iterator instead. This means, a code like this:

List<Integer> intList = new ArrayList<>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
for(Integer i : intList) {
    i *= 2;
}

Is similar to:

for(Iterator<Integer> it = intList.iterator(); it.hasNext(); ) {
    Integer i = it.next();
    i *= 2;
}

Related info:

  • Is Java "pass-by-reference" or "pass-by-value"?
like image 61
Luiggi Mendoza Avatar answered Sep 21 '22 13:09

Luiggi Mendoza