Java modification of elements in foreach

I learn Java myself; and therefore the code below has no function other than training / testing.

In fact, I'm trying to modify the elements of an Integer array (namely, to reduce them in half), while in a foreach loop.

I must note that I am not reordering, not adding or removing elements; just changing their meanings.

Here is my code:

Logger.describe("Now copying half of that array in to a new array, and halving each element");
Integer[] copyArray = new Integer[DEFAULT_SAMPLE_SIZE / 2];     
System.arraycopy(intArray, 0, copyArray, 0, DEFAULT_SAMPLE_SIZE / 2);
for (Integer x : copyArray) x /= 2;
Logger.output(Arrays.deepToString(copyArray));

However, the original array (intArray) is as follows:

[47, 31, 71, 76, 78, 94, 66, 47, 73, 21]

And the output of copyArray:

[47, 31, 71, 76, 78]

So, although the size of the array was halved, the elements (integers) also did not halve. So what am I doing wrong?

thank

+5
source share
4 answers

You cannot do this in a foreach loop.

for (int i=0; i<copyArray.length;i++)
    copyArray[i] /= 2;

. Integer , ( ).

: , , , , autoboxing/unboxing, :

copyArray[i] = Integer.valueOf(copyArray[i].intValue()/2);
+13
for (int i = 0; i< copyArray.length; i++) {
    copyArray[i] = new Integer(x /2);
}

.

+1
int counter = 0;
for(int x : copyArray)
{
        x /= 2;
        copyArray[counter++] = x;
}

x, copyArray

+1

, foreach, , . :

Logger.describe("Now copying half of that array in to a new array, and halving each element");
Integer[] copyArray = new Integer[DEFAULT_SAMPLE_SIZE / 2];     
System.arraycopy(intArray, 0, copyArray, 0, DEFAULT_SAMPLE_SIZE / 2);
    for (int i = 0; i < copyArray.length; i++) {
        copyArray[i] /= 2;
    }
Logger.output(Arrays.deepToString(copyArray));
0

All Articles