foreach循环
来源:互联网 发布:java中接口怎么写 编辑:程序博客网 时间:2024/06/05 09:50
没有forach之前,我们需要这样遍历一个集合
如果用foreach只需要这样
是不是省事多了,不用索引值,不用判断是否越界。
foreach集合原理
源代码
我们知道集合都实现了iterator接口
因为集合实现了Iterator接口,所以遍历时走的Iterator的方法,但是foreach不只可以遍历集合,还可以遍历数组?
同样,看反编译后的代码
for(int i=0; i<list.size; i++){//.....}
如果用foreach只需要这样
List<String> list = new ArrayList<String>();for(String e : list){//}
是不是省事多了,不用索引值,不用判断是否越界。
foreach集合原理
源代码
List<String> a = new ArrayList<String>(); a.add("1"); a.add("2"); a.add("3"); for(String temp : a){ System.out.print(temp); }反编译后的代码
List a = new ArrayList();a.add("1"); a.add("2"); a.add("3"); String temp; for(Iterator i$ = a.iterator(); i$.hasNext(); System.out.print(temp)){ temp = (String)i$.next();}foreach集合相当于获取迭代器(a.iterator),通过判断是否有下一个元素(i.hasNext()∗∗),,然后移动光标(∗∗i.next());,执行操作(System.out.print(temp))
我们知道集合都实现了iterator接口
public interface Iterator<E> { boolean hasNext(); E next(); void remove();}public interface Collection<E> extends Iterable<E>foreach数组
因为集合实现了Iterator接口,所以遍历时走的Iterator的方法,但是foreach不只可以遍历集合,还可以遍历数组?
同样,看反编译后的代码
String[] arr = {"1","2"}; for(String e : arr){ System.out.println(e); }反编译后代码
String arr[] = { "1", "2" }; String arr$[] = arr; int len$ = arr$.length; for(int i$ = 0; i$ < len$; i$++) { String e = arr$[i$]; System.out.println(e); }可以看到foreach数组,走的是for(int i=0; i< len; i++)经典模式。
阅读全文
0 0
- foreach循环
- foreach循环
- foreach循环
- foreach 循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- foreach循环
- 学习总结-Thinking In Java Chapter 13 strings
- easyui table 属性页面 及增 删 改查按钮 close按钮
- Anguar.js介绍
- Java 集合系列03之 ArrayList详细介绍(源码解析)和使用示例
- BZOJ 3676 回文串
- foreach循环
- 运算符、表达式和语句
- 仿射变换和SURF特征点匹配
- Wins系统带选项复制命令robocopy的操作方法介绍
- c# 发送qq邮箱本地正常 布置到服务器上后出现的异常
- 求最长上升子序列
- 【分析】Ceph系统架构
- “盛大游戏杯”第15届上海大学程序设计联赛夏季赛暨上海高校金马五校赛
- 关于表达式中除数为0的容错机制的处理