高级for循环(foreach)
来源:互联网 发布:java 中接口interface 编辑:程序博客网 时间:2024/06/06 18:50
For-Each循环
For-Each循环也叫增强型的for循环,或者叫foreach循环。
For-Each循环是JDK5.0的新特性(其他新特性比如泛型、自动装箱等)。
For-Each循环的加入简化了集合的遍历。
在遍历数组、集合方面
其语法如下:
for(type element: array) { System.out.println(element); }
例子
其基本使用可以直接看代码:
代码中首先对比了两种for循环;之后实现了用增强for循环遍历二维数组;最后采用三种方式遍历了一个List集合。
import java.util.ArrayList;import java.util.Iterator;import java.util.List;public class ForeachTest{ public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; System.out.println("----------旧方式遍历------------"); //旧式方式 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("---------遍历二维数组-------------"); //遍历二维数组 int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ; for(int[] row : arr2) { for(int element : row) { System.out.println(element); } } //以三种方式遍历集合List List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); System.out.println("----------方式1-----------"); //第一种方式,普通for循环 for(int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } System.out.println("----------方式2-----------"); //第二种方式,使用迭代器 for(Iterator<String> iter = list.iterator(); iter.hasNext();) { System.out.println(iter.next()); } System.out.println("----------方式3-----------"); //第三种方式,使用增强型的for循环 for(String str: list) { System.out.println(str); } }}
For-Each循环的缺点:丢掉了索引信息。
当遍历集合或数组时,如果需要访问集合或数组的下标,那么最好使用旧式的方式来实现循环或遍历,而不要使用增强的for循环,因为它丢失了下标信息。
阅读全文
0 0
- 高级for循环(foreach)
- for 循环,foreach循环
- Java foreach 高级for
- 增强的for循环(或foreach)
- Java foreach(加强for循环)
- 增强for循环 -- foreach循环
- for循环和foreach循环
- JSTL forEach标签(for循环)
- forEach 当 for循环使用
- foreach语句:增强for循环
- Objective-C中的For和ForEach循环(For and ForEach Loops in Objective-C )
- 增强的for循环--foreach循环
- for 循环 foreach 循环输出练笔
- for循环和foreach循环的区别?
- Java中的增强for循环(foreach)的实现原理
- java的增强性for循环(foreach)访问数组
- 熊猫学猿--(第八竹--循环 for、foreach)
- 循环语句:for;while;for while;foreach
- 20170807ceph入门(一)——ceph中rados对象创建以及文件上传与下载
- 利用python将execl的数据导入hive
- 在 Mac OS X 上安装 TensorFlow
- OpenCV自学笔记24. Raspberry pi +OpenCV 读取摄像头
- socket 的关闭
- 高级for循环(foreach)
- java多线程----关于join方法的注意点,以及守护线程的小结
- Mac环境下Myeclispe2015工具的安装与破解
- PHP 基础—— include 和 require
- hdu1852 Beijing 2008 x^y的因子和2.0
- pandas入门——loc与iloc函数
- 二叉树的静态实现
- Linux 命令全称
- python序列化