天天看点

Java语法糖之foreach

  语法糖是一种几乎每种语言或多或少都提供过的一些方便程序员开发代码的语法,它只是编译器实现的一些小把戏罢了,编译期间以特定的字节码或者特定的方式对这些语法做一些处理,开发者就可以直接方便地使用了。这些语法糖虽然不会提供实质性的功能改进,但是它们或能提高性能、或能提升语法的严谨性、或能减少编码出错的机会。Java提供给了用户大量的语法糖,比如泛型、自动装箱、自动拆箱、foreach循环、变长参数、内部类、枚举类、断言(assert)等。

  本篇主要是讲解foreach,foreach的语法经过编译之后解析成什么呢?

  首先来看一个例子:

  对这个类进行反编译:

  打开f1.txt,结果如下所示:

  反编译出来的内容很多,看不懂也没关系,关键看到Iterator这个标志,其实在对有实现Iterable接口的对象采用foreach语法糖的话,编译器会将这个for关键字转化为对目标的迭代器使用。

  上面的代码会被转化为如下的代码:

注:如果要想使自己自定义的类可以采用foreach语法糖就必须实现Iterable接口。

  细心的朋友可能会注意到,java中的数组也可以采用foreach的语法糖,但是数组并没有实现Iterable接口呀。

  下面再举一个例子:

  反编译结果:

  看不懂?同样没关系~这里可以注意到数组的foreach语法糖并没有采用Iterable实现转换。如上面的信息只是涉及一些压栈出站的内容。真正的解析结果如下所示:

  可以看到对于数组而言,其实就是转换为普通的遍历而已;

  关于foreach语法糖的信息就这样结束了嚒? 显然没有!

  对于实现RandomAccess接口的集合比如ArrayList,应当使用最普通的for循环而不是foreach循环来遍历,所以第一个例子中有欠妥之处。

  首先看一下jdk1.7中对RandomAccess接口的定义:

java.util

Interface RandomAccess

All Known Implementing Classes:

ArrayList, AttributeList, CopyOnWriteArrayList, RoleList, RoleUnresolvedList, Stack, Vector

public 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.

从以下版本开始:

1.4

  看不懂英文也没关系,我来解释一下最后一句加粗的话:实际经验表明,实现RandomAccess接口的类实例,假如是随机访问的,使用普通for循环效率将高于使用foreach循环;反过来,如果是顺序访问的,则使用Iterator会效率更高。

  可以使用类似如下的代码作判断:

其实如果看过ArrayList源码的同学也可以注意到:ArrayList底层是采用数组实现的,如果采用Iterator遍历,那么还要创建许多指针去执行这些值(比如next();hasNext())等,这样必然会增加内存开销以及执行效率。

  

附:javap(反汇编命令)详解   javap是JDK自带的反汇编器,可以查看java编译器为我们生成的字节码。通过它,我们可以对照源代码和字节码,从而了解很多编译器内部的工作。   语法:   javap [ 命令选项 ] class…   javap 命令用于解析类文件。其输出取决于所用的选项。若没有使用选项,javap 将输出传递给它的类的 public 域及方法。javap 将其输出到标准输出设备上。 命令选项 -help 输出 javap 的帮助信息。 -l 输出行及局部变量表。 -b 确保与 JDK 1.1 javap 的向后兼容性。 -public 只显示 public 类及成员。 -protected 只显示 protected 和 public 类及成员。 -package 只显示包、protected 和 public 类及成员。这是缺省设置。 -private 显示所有类和成员。 -J[flag] 直接将 flag 传给运行时系统。 -s 输出内部类型签名。 -c 输出类中各方法的未解析的代码,即构成 Java 字节码的指令。 -verbose 输出堆栈大小、各方法的 locals 及 args 数,以及class文件的编译版本 -classpath[路径] 指定 javap 用来查找类的路径。如果设置了该选项,则它将覆盖缺省值或 CLASSPATH 环境变量。目录用冒号分隔。 - bootclasspath[路径] 指定加载自举类所用的路径。缺省情况下,自举类是实现核心 Java 平台的类,位于 jrelibt.jar 和 jrelibi18n.jar 中。 -extdirs[dirs] 覆盖搜索安装方式扩展的位置。扩展的缺省位置是 jrelibext。