Why does this cycle for each cycle not work?

In this code, why is my array not initialized, how do I want it? Is each cycle not intended for this, or am I just not using it correctly?

    int[] array = new int[5];

    //initialise array -> Doesn't work! Array still full of 0's
    for(int i : array)
        i = 24;
+5
source share
5 answers

The for-each loop will not work for this case. You cannot use a for loop for each loop to initialize an array. Your code:

int[] array = new int[5];
for (int i : array) {
    i = 24;
}

will translate something like the following:

int[] array = new int[5];
for (int j = 0; j < array.length; j++) {
    int i = array[j];
    i = 24;
}

, . , , , , , . . .

, , . for for-each - . "i" ( "int i" ) "array[index]".

Date, , , :

Date[] array = new Date[5];
for (Date d : array) {
    d = new Date();
}

:

Date[] array = new Date[5];
for (int i = 0; i < array.length; i++) {
    Date d = array[i];
    d = new Date();
}

, , . , .

. , .class, jad, . , Sun Java (1.6) :

int array[] = new int[5];
int ai[];
int k = (ai = array).length;
for(int j = 0; j < k; j++)
{
    int i = ai[j];
    i = 5;
}
+14

i - int , . .

+5

java.util.Arrays.fill(array, 24)

. , .

+4

int , , , ...

. Xs, X - , , , (, setValue).

ints , int , , , i. i, .

+3

:

int[] array = new int[5];

// initialise array -> Will work now
for(int i = 0 ; i< array.length ; i++)
    array[i] = 24 ;
0

All Articles