Java Array Loop Behavior

I tested several different ways of multiplying array elements with a constant.

I got different results depending on how I go through the array, and I had trouble understanding this (I'm pretty new to Java and still get information on how things are passed or referenced).

Test 1

int[] array = {1, 2, 3, 4}; for (int number : array) { number *= 2; } 

The result of unmodified array elements:

 {1, 2, 3, 4} 

It seems that number is not the actual element of the array, but a new int that is initialized with its value. It is right?


Test 2

I thought that using an array of objects could work, assuming that number is a reference to the actual element of the array. Here is my test for using Integer instead of int :

 Integer[] array = {1, 2, 3, 4}; for (Integer number : array) { number *= 2; } 

Again, as a result of which the elements of the array are not modified:

 {1, 2, 3, 4} 

Test 3

After some scratching on my head, I tried another loop method, for example:

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

The result of the multiplication of array elements:

 {2, 4, 6, 8} 

This end result makes sense to me, but I don’t understand the results of the second test (or, first of all, for this). Until now, I have always believed that the loop used in tests 1 and 2 was just a shorthand for the loop used in test 3, but they are clearly different.

Why does this not work as I expected? Why are these loops different?

+5
source share
1 answer

This is because the extended for loop uses a copy of the value in the array. Code in

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

Similar to:

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

The same thing happens when using Integer[] .

Also, when you use the extended for loop in Iterable , for example. List , it uses an iterator instead. This means that such code looks 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; } 

Similar to:

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

Additional Information:

+6
source

Source: https://habr.com/ru/post/1201863/


All Articles