语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的字节码或者特定的方式对这些语法做一些处理,开发者就可以直接方便地使用了。这些语法糖虽然不会提供实质性的功能改进,但是它们或能提高性能、或能提升语法的严谨性、或能减少编码出错的机会。Java提供给了用户大量的语法糖,比如泛型、自动装箱、自动拆箱、foreach循环、变长参数、内部类、枚举类、断言(assert)等。
package com.learn.foreach;import java.util.ArrayList;
import java.util.List;public class ForeachTest {public static void main(String[] args) {List<String> list = new ArrayList<String>();list.add("s1");list.add("s2");for (String s : list) {System.out.println(s);}}
}
反编译出来的内容很多,看不懂也没关系,关键看到Iterator这个标志,其实在对有实现Iterable接口的对象采用foreach语法糖的话,编译器会将这个for关键字转化为对目标的迭代器使用。上面的代码会被转化为如下的代码:package com.learn.foreach;import java.util.ArrayList;
import java.util.List;import com.learn.iterator.Iterator;public class ForeachTest {/*** 编译器会对没有显示构造函数的类添加一个默认的构造函数,* 这个阶段是在语义分析阶段完成的*/public ForeachTest() {super();}public static void main(String[] args) {List<String> list = new ArrayList<String>();list.add("s1");list.add("s2");for(Iterator it = (Iterator) list.iterator();it.hasNext();) {String s = (String)it.next();{System.out.println(s);}}}
}
注:如果要想使自己自定义的类可以采用foreach语法糖就必须实现Iterable接口。
java中的数组也可以采用foreach的语法糖,但是数组并没有实现Iterable接口呀。
package com.learn.foreach;public class ForeachTest2 {public static void main(String[] args) {String arr[] = {"s1","s2"};for (String s : arr) {System.out.println(s);}}}
数组的foreach语法糖并没有采用Iterable实现转换。真正的解析结果如下所示:package com.learn.foreach;public class ForeachTest2 {public ForeachTest2() {super();}public static void main(String[] args) {int arr[] = {1,2};int [] arr$ = arr;for(int len$ = arr$.length; i$=0; i$<len$; ++i$) {int i = arr$[i$];{System.out.println(i);}}}}
可以看到对于数组而言,其实就是转换为普通的遍历而已;关于foreach语法糖的信息就这样结束了嚒? 显然没有!对于实现RandomAccess接口的集合比如ArrayList,应当使用最普通的for循环而不是foreach循环来遍历,所以第一个例子中有欠妥之处。
首先看一下jdk1.7中对RandomAccess接口的定义:java.util
Interface RandomAccessAll Known Implementing Classes:
ArrayList, AttributeList, CopyOnWriteArrayList, RoleList, RoleUnresolvedList, Stack,
Vectorpublic interface RandomAccess
Marker interface used by List implementations to indicate that they support fast (generally constant time) random access. The primary purpose of this interface is to allow generic algorithms to alter their behavior to provide good performance when applied to either random or sequential access lists.
The best algorithms for manipulating random access lists (such as ArrayList) can produce quadratic behavior when applied to sequential access lists (such as LinkedList). Generic list algorithms are encouraged to check whether the given list is an instanceof this interface before applying an algorithm that would provide poor performance if it were applied to a sequential access list, and to alter their behavior if necessary to guarantee acceptable performance.
It is recognized that the distinction between random and sequential access is often fuzzy. For example, some List implementations provide asymptotically linear access times if they get huge, but constant access times in practice. Such a List implementation should generally implement this interface. As a rule of thumb, a List implementation should implement this interface if, for typical instances of the class, this loop:
for (int i=0, n=list.size(); i < n; i++)
list.get(i);runs faster than this loop:
for (Iterator i=list.iterator(); i.hasNext(); )
i.next();This interface is a member of the Java Collections Framework.

Java语法糖之foreach相关推荐

  1. Java语法糖1:可变长度参数以及foreach循环原理

    语法糖 接下来几篇文章要开启一个Java语法糖系列,所以首先讲讲什么是语法糖.语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的 ...

  2. java语法糖效率高吗_打包 Java将持续向“高糖”方向发展,你真的了解Java语法糖吗? _好机友...

    Java语法糖概念 1. 语法糖Syntactic Sugar 糖衣语法,方便开发人员使用,JVM并不识别,会在编译阶段解语法糖,还原为基础语法. 2. com.sun.tools.javac.mai ...

  3. JAVA语法糖(全)

    JAVA语法糖(全) 目录 概述 字符串拼接 条件编译 断言 枚举与Switch语句 字符串与Switch语句 可变参数 自动装箱/拆箱 枚举 内部类 泛型擦除 增强for循环 lambda表达式 t ...

  4. 65.Java语法糖

    65.Java语法糖 语法糖(Syntactic Sugar),也称糖衣语法,是由英国计算机学家 Peter.J.Landin 发明的一个术语,指在计算机语言中添加的某种语法,这种语法对语言的功能并没 ...

  5. Java 语法糖详解

    语法糖(Syntactic Sugar),也称糖衣语法,是由英国计算机学家 Peter.J.Landin 发明的一个术语,指在计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序 ...

  6. Jvm 系列(十一)Java 语法糖背后的真相

    语法糖(Syntactic Sugar),也叫糖衣语法,是英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语.指的是,在计算机语言中添加某种语法,这些语法糖虽然不会对语言 ...

  7. Java中switch参数传null会引起异常——Java 语法糖

    问题 switch 参数不能是null,swicth(null)会报java.lang.NullPointerException异常 查找原因 为什么会这样呢,查找一下原因: 找到编译后的class文 ...

  8. java 语法糖 字符串,java中的一些语法糖

    Java中的语法糖 语法糖的定义:语法糖指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,并没有给语言添加什么新东西,但是更方便程序员使用.通常来说使用语法糖能够增加程序的可读性,从而减少 ...

  9. 全网最全的 Java 语法糖指南

    写在前面 本文隶属于专栏<100个问题搞定Java虚拟机>,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢! 本专栏目录结构和文献引用请见100个问题搞定Java ...

最新文章

  1. 预、自训练之争:谷歌说预训练虽火,但在标注数据上自训练更有效
  2. Google推出的新服务:Docs Spreadsheets
  3. Android之HTTP预备知识
  4. 单机编程c语言,完美的8051单机C语言编程模板.doc
  5. 2018-2019-2 20165114《网络对抗技术》Exp4 恶意代码分析
  6. JavaScript入门(part12)--内置对象
  7. 三极管和MOS管有什么不一样?用MOS管还是三极管?
  8. orcad如何设置模块化设计_这个模块化的办公桌让您设计每一个元素,以创造完美的工作设置...
  9. jsp if else c标签 总结
  10. 流畅的python 数据模型
  11. sql server分布式_如何安装,配置和使用SQL Server分布式重播
  12. 声笔码和声笔数码单字效率分析
  13. 什么?云数据库也能C位出道?
  14. Axure版PRD产品需求文档(教程+下载)
  15. 微云html网页,微云收藏在哪里_以及腾讯微云收藏网页版怎么用? - 软件教程 - 格子啦...
  16. 计算机英语格式怎么写,26个英文字母,正确的书写格式,孩子真的会吗?
  17. 64个 360 评估的提问样例
  18. EntityConnection ConnectionString
  19. 大数据背景下谋划检务公开
  20. popstate返回上一级问题。

热门文章

  1. Jquery 温习,温故而知新,可以为师矣
  2. 技术人员如何创业《四》- 打造超强执行力团队(转载)
  3. Redis Lua脚本中学教程(上)
  4. 1112 Stucked Keyboard
  5. 安装Jumpserver
  6. grenndao 插入表数据报错
  7. linux监控命令详解
  8. sql编写将时间转换年月日 时分格式
  9. Gartner:2013-2014年全球MSS市场分析
  10. 【转】SQL注入攻击防御深层思考