廖雪峰Java1-4数组操作-1遍历数组
1.遍历数组
- for循环通过下标遍历数组
- for each直接遍历数组所有元素
int[] ns1 = {1, 34, 9, 16, 25};
for(int i = 0;i<ns1.length;i++){
System.out.print(ns1[i]+"\t");
}
System.out.println();
String[] ns2 = {"Tom", "Jerry", "Green", "Cury", "Tim"};
for (String i:ns2){
System.out.print(i+"\t");
}
![](https://img2018.cnblogs.com/blog/1418970/201901/1418970-20190111084638845-21067994.png)
![](https://img2018.cnblogs.com/blog/1418970/201901/1418970-20190111085640620-259286271.png)
3.总结:
遍历数组可以使用for循环:普通for循环可以访问数组索引;for-each循环直接迭代每个元素,无法直接访问索引。
Arrays.toString()用于快速打印数组内容