Foreach is a new, more concise syntax introduced by Java SE5, which brings great convenience in traversing arrays and containers, but has its limitations.
Statement format for foreach:
for (element type T element variable x: Traverse object obj) {
A Java statement that references X;
}
The traversal of a foreach simplified array
Example one (one-dimensional array):
1 ImportJava.util.Random;2 Public classForeach {3 Public Static voidMain (string[] args) {4Random Rand =NewRandom ();5 int[] t =New int[5];6 //initializing an array7 for(inti=0;i<t.length;i++)8T[i] = rand.nextint (100);9 Ten //iterating through an array using foreach One for(intx:t) ASystem.out.print (x + ""); - } - } the /* - * Output Result: - About - * + */
Example two (two-dimensional array)
1 Public classForeach {2 Public Static voidMain (string[] args) {3 //initializing an array4 int[] t = {5{2,3,4,5},6{1,6,7,8}7 };8 9 //iterating through an array using foreachTen for(intx[]:t) { One for(intm:x) ASystem.out.print (M + ""); - System.out.println (); - } the } - } - /* - * Output Result: + * 2 3 4 5 - * 1 6 7 8 + * A */
However, it is worth noting that foreach is unable to complete the assignment, that is, the array is only "read-only" for the foreach statement.
Example three (foreach cannot complete assignment)
1 ImportJava.util.Random;2 Public classForeach {3 Public Static voidMain (string[] args) {4Random Rand =NewRandom ();5 int[] t =New int[5];6 //initializing an array7 for(inti=0;i<t.length;i++)8T[i] = rand.nextint (100);9 Ten //iterating through an array using foreach One for(intx:t) ASystem.out.print (x + ""); - System.out.println (); - the //Assignment with foreach (note that this is the wrong approach) - for(intx:t) -x = Rand.nextint (100); - //iterate through the array again + for(intx:t) -System.out.print (x + ""); + } A } at /* - * Output Result: - * All in all - * All in all - * - */
As can be seen from the above example three, foreach cannot be assigned to an array, and foreach is performed as follows
1 for (T x:obj) {2 x = Obj[i]; 3 x = random number; 4 5 }
Therefore, it is not possible to assign a value to an array.
Use of foreach in Java