For-each循环一般用于遍历数组或集合类(例如,ArrayList)。
句法:
for (type var : array) { statements using var; }
相当于:
for (int i=0; i<arr.length; i++) { type var = arr[i]; statements using var; }
For-each循环的实例:
// Java program to illustrate // for-each loop class For_Each { public static void main(String[] arg) { { int[] marks = { 125, 132, 95, 116, 110 }; int highest_marks = maximum(marks); System.out.println("The highest score is " + highest_marks); } } public static int maximum(int[] numbers) { int maxSoFar = numbers[0]; // for each loop for (int num : numbers) { if (num > maxSoFar) { maxSoFar = num; } } return maxSoFar; } }
输出:
The highest score is 132
但是for-each也有其局限性,更多可以参照:在Java中的For-each循环
无限循环:实现任何类型的循环时最常见的错误之一是,它可能永远不会退出,也就是循环运行无限的时间。出于某种原因,条件失败时会发生这种情况。
例子:
//Java program to illustrate various pitfalls. public class LooppitfallsDemo { public static void main(String[] args) { // infinite loop because condition is not apt // condition should have been i>0. for (int i = 5; i != 0; i -= 2) { System.out.println(i); } int x = 5; // infinite loop because update statement // is not provided. while (x == 5) { System.out.println("In the loop"); } } }
另一个缺陷是你可能通过循环向你的collection对象中添加了一些东西,你可能会用完内存。如果尝试执行下面的程序,一段时间后,内存不足异常将被抛出。
//Java program for out of memory exception. import java.util.ArrayList; public class Integer1 { public static void main(String[] args) { ArrayList<Integer> ar = new ArrayList<>(); for (int i = 0; i < Integer.MAX_VALUE; i++) { ar.add(i); } } }
输出:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.util.Arrays.copyOf(Unknown Source) at java.util.ArrayList.grow(Unknown Source) at java.util.ArrayList.ensureCapacityInternal(Unknown Source) at java.util.ArrayList.add(Unknown Source) at article.Integer1.main(Integer1.java:9)