數組和集合可以用for增強來遍歷:
int[] arr = { 1, 2, 3, 4, 5 };
// 舊式方式
for (int i = 0; i < arr.length; i++)
{
System.out.println(arr[i]);
}
System.out.println("--------------------------");
// 新式方式,增強的for循環
for (int element : arr)
{
System.out.println(element);
}
System.out.println("--------------------------");
String[] names = { "hello", "world", "welcome" };
for (String name : names)
{
System.out.println(name);
}
System.out.println("--------------------------");
int[][] arr2 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for(int[] row : arr2)
{
for(int element : row)
{
System.out.println(element);
}
}
System.out.println("--------------------------");
Collection<String> col = new ArrayList<String>();
col.add("one");
col.add("two");
col.add("three");
for(String str : col)
{
System.out.println(str);
}