Java的修改元素在foreach [英] Java Modifying Elements in a foreach

查看:504
本文介绍了Java的修改元素在foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习Java对我自己的;以下因此code没有比学习/测试等功能。

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.

下面是我的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));

然而,原始阵列(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;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);

这篇关于Java的修改元素在foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆