Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
986 views
in Technique[技术] by (71.8m points)

arrays - Java Modifying Elements in a foreach

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't do that in a foreach loop.

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

Else you are not assigning it back into the array. Integer objects are immutable by the way so can't modify them (creating new ones though).

Updated from comment: Beware though that there are a few things going on, autoboxing/unboxing for example, roughly:

copyArray[i] = Integer.valueOf(copyArray[i].intValue()/2);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...