Java在foreach中修改元素 [英] Java Modifying Elements in a foreach
问题描述
我正在自学 Java;因此下面的代码除了学习/测试之外没有其他功能.
I'm learning Java on my own; and therefore the code below has no function other than for learning/testing.
本质上,我试图在 foreach 循环中修改整数数组的元素(即,将它们减半).
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.
这是我的代码:
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));
然而,原来的数组(intArray)是这样的:
However, the original array (intArray) is this:
[47, 31, 71, 76, 78, 94, 66, 47, 73, 21]
copyArray 的输出是:
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?
谢谢
推荐答案
你不能在 foreach 循环中这样做.
You can't do that in a foreach loop.
for (int i=0; i<copyArray.length;i++)
copyArray[i] /= 2;
否则您不会将其分配回数组.顺便说一下,Integer
对象是不可变的,因此不能修改它们(尽管创建新的).
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);
这篇关于Java在foreach中修改元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!