Java Modifying Elements in a foreach

前端 未结 4 1157
迷失自我
迷失自我 2020-12-04 02:18

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 Inte

相关标签:
4条回答
  • 2020-12-04 02:36
    int counter = 0;
    for(int x : copyArray)
    {
            x /= 2;
            copyArray[counter++] = x;
    }
    

    Your program just modified the value of variable x , not the values within the blocks of array copyArray

    0 讨论(0)
  • 2020-12-04 02:37
    for (int i = 0; i< copyArray.length; i++) {
        copyArray[i] = new Integer(x /2);
    }
    

    should work.

    0 讨论(0)
  • 2020-12-04 02:59

    I think that you can NOT use the foreach loop construct in order to modify the elements of the array you are iterating. Instead, you need to use a classic for loop like so:

    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 讨论(0)
  • 2020-12-04 03:02

    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);
    
    0 讨论(0)
提交回复
热议问题