Java foreach 原理

作者: IT_Matters | 来源:发表于2016-06-12 19:57 被阅读275次

from:http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work

forEach是JDK1.5以后出现的新特性,那么以下这段forEach代码和普通的for循环又有什么不同呢?

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
  System.out.println(item);
}

该代码编译过程中实际上会被翻译成以下代码。

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
   String item = i.next(); 
   System.out.println(item);
}

这适用于实现了Iterable
接口的类。
此外对于数组来说,就会使用一个下标,每次遍历时检查是否到达数组的边界,如果不就前进一步,就和普通的for写法一样。

int[] test = new int[] {1,4,5,7};
for (int intValue : test) {
 // do some work here on intValue
}
int[] test = new int[] {1,4,5,7};
for (int i = 0; i < test.length; i++) { 
    int intValue = test[i]; 
   // do some work here on intValue
}

相关文章

  • Java foreach 原理

    from:http://stackoverflow.com/questions/85190/how-does-th...

  • Java中Foreach原理

    介绍 对于之前的for循环在jvm中如何实现9. jvm9:字节码指令,我进行了思考分析,而对于我们日常开发却经常...

  • Java foreach 循环原理

    foreach是java的语法糖,所谓语法糖就是通过编译器或者其它手段优化了代码,给使用带来了遍历。比如,没有fo...

  • Java 几种循环方式

    1、java循环分类 Iterator、for、foreach、Stream.forEach 2、java迭代器I...

  • foreach原理

    纯粹是个人学习总结,如有不对的地方请吐槽。 在平时Java程序中,应用比较多的就是对Collection集合类的f...

  • Java中foreach的遍历顺序

    foreach结构 Java的foreach是一种增强的for结构,其形式如下 foreach的语义非常清晰:对于...

  • Java的forEach() 与 groovy的forEach(

    Java的forEach()常用写法(JDK 1.8以后):userList.forEach(user-> {Sy...

  • Java8 forEach

    Java8 forEach Java forEach 是一种实用程序方法,用于迭代集合(如列表、集或映射)和流,并...

  • [转]MyBatis使用Map传参批量插入数据

    参数部分 java MyBatis的Mapper.xml foreach标签解释: foreach标签可使用的地方...

  • Java中foreach循环的实现原理

    1、背景知识介绍 java foreach 语法是在jdk1.5时加入的新特性,主要是当作for语法的一个增强,那...

网友评论

    本文标题:Java foreach 原理

    本文链接:https://www.haomeiwen.com/subject/kvaedttx.html