我们直接看代码就明白了,很简单
代码:
import java.util.ArrayList;
/*
* 使用foreach遍历集合和数组
*/
public class Use_foreach_遍历 {
public static void main(String[] args) {
Use_foreach_遍历 u = new Use_foreach_遍历();
u.GoThrowArray();
u.GoThrowList();
}
// foreach遍历数组
public void GoThrowArray() {
int[] arr = new int[] {1,2,3,4,5,6};
//使用与数组同类型的变量接收a的返回值
for (int i : arr) {
System.out.print(i+"\t");
}
System.out.println("\n");
}
// foreach遍历集合
public void GoThrowList() {
ArrayList a = new ArrayList();
a.add(123);
a.add("你好");
a.add(456);
//使用Object的变量接收a的返回值
for (Object object : a) {
System.out.print(object+"\t");
}
}
}
结果: