Java arrays and use a foreach loop

Java arrays and use a foreach loop

Apart from anything else, the first rejection of a simple program:

final int NUM= 10;
int[] arrays = new int[NUM];
System.out.println(arrays.length);//10
for(int i = 0;i<5;i++){
    arrays[i] = i;//赋值
}
//foreach
for(int element:arrays){
    System.out.print(element+" ");
}
// 0 1 2 3 4 0 0 0 0 0
  • A dynamically created array of arrays, the specified array length of 10.
  • Index from 0 to 1 minus the length of the end, out of range error.
  • With the lengthobtained attribute length of the array , for example arrays.length.
  • 数组名[index]Access array elements can be assignment.
  • Since dynamic initialization, no part of the system default value of 0 is assigned.
  • Print output using a foreach loop, it is for Java arrays and collections born circulation.

foreach loop

format:

for(元素类型 元素:数组名){...}
  • As it can be seen, compared to the for loop, foreach do not care about the length of the array does not need to rely on the value of the index to access array elements, but through all the elements .
  • The array element type and type the same as it always, or gnaw into them.
  • To see a saying in the book, I was very impressed: for the each Element in Array , meaning that each element in the array.

note:

int []arrays = {1,2,3,4,5};
// int i;
System.out.println("使数组中每个元素加1");
for(int i:arrays){
    i+=1;
    System.out.print(i+" ");
}
System.out.println();
System.out.println("修改后:");
for(int j:arrays){
    System.out.print(j+" ");
}   
/**
使数组中每个元素加1
2 3 4 5 6
修改后:
1 2 3 4 5*/
  • In the foreach the array element assignment and it has no effect.
  • During foreach loop, in fact, the system will assign a temporary element of the array variable, and thus would not change the original array.

Guess you like

Origin www.cnblogs.com/summerday152/p/11873901.html