I'm learning Java on my own; and therefore the code below has no function other than for learning/testing.
Essentially I'm trying to modify the elements of an Integer array (namely, halving them) whilst in a foreach loop.
I should note that I'm not re-ordering, adding, or deleting elements; simply changing their values.
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 this:
[47, 31, 71, 76, 78, 94, 66, 47, 73, 21]
And the output of copyArray is:
[47, 31, 71, 76, 78]
So although the array has been halved in size, the elements (Integers) haven't also been halved in value. So what am I doing wrong?
Thank you
x/2
, it isn't modifying the object's value, but automatically converts it to a primitiveint
and divides it, therefore yourInteger
instance is not affected. – Klutex = x/2
is ax = new Integer(x.intValue()/2)
. So since you aren't adding it back to the array, you aren't getting your array elements modified. – Klute