Java语法糖之foreach-编程开发技术_第1页
Java语法糖之foreach-编程开发技术_第2页
Java语法糖之foreach-编程开发技术_第3页
Java语法糖之foreach-编程开发技术_第4页
Java语法糖之foreach-编程开发技术_第5页
已阅读5页,还剩11页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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

2、编译z后解析成什么呢? 首先来看一个例子:package foreach;import java.util. arraylist;import java.util. list;public class foreachtestpublic static void main(string args)lising> list 二 new arraylislist. add("sl);list. addc,s2,/);for(string s : list)system, out. println(s);对这个类进行反编译:javac foreachtest. javajavap -v

3、erbose foreachtest > fl. txt打开fl. txt,结果如下所示:classfile /d:/workspace_jee/javatest/src/foreach/foreachtest classlast modified 2016-2-25; size 798 bytesmd5 checksum c64e6f81f34dldfc7834ad8d5b3bl801compiled from foreachtest. java" public class foreach. foreachtestsourccfilc: foreachtest java,zm

4、inor version: 0major version: 51flags: acc_public, acc_superconstant pool:/ java/uti1/arraylist/ si/ s2/#1 =mcthodrcf#14. #26java/lang/object.() v#2 =class#27#3 二methodref#2.#26java/util/arraylist. z,<ini t>,z: () v#4 = string#28#5 = interfacemethodref #29. #30 java/util/list. add: (ljava/lang

5、/object;)z#6 二 string#31#7 二 interfacemethodref #29. #32 java/util/list iterator:()ljava/util/itcrator;#8 = interfacemethodref #33.#34/java/util/iterator hasnext:() z#9 二 interfacemethodref #33.#35/java/uti1/iterator, next:()ljava/1ang/object;#10 = class#36/ j ava/1ang/string#11 = fieldref#37.#38/ja

6、va/lang/system. out:ljava/io/printstream;#12 二 methodref#39. #40/java/io/printstream. printin:(ljava/1ang/string;)v#13 = class#41/forcach/forcachtcst#14 = class#42/java/lang/object#15 = utf8<init>#16 二 utf8()v#17 二 utf8code#18 = utf8lincnumbcrtab1c#19 = utf8main#20 = utf8(ljava/lang/string;)v#

7、21 二 utf8stackmaptable#22 二 class#43/java/uti1/list#23 = class#44/java/util/iterator#24 = utf8sourcefile#25 = utf8foreachtest.java#26 二 nameandtype#15:#16/,z<init>,z:()v#28 = utf8si#29 二 class#43/ java/util/list#30 二 nameandtype#45:#46/add: (ljava/lang/objcct;)z#31 = utf8s2#32 = nameandtype#47

8、:#48/iterator: ()ljava/util/iterator;#33 = class#44/java/util/iterator#34 二 nameandtype#49:#50/hasnext: () z#35 = nameandtype#51:#52/next: ()ljava/lang/object;#36 二 utf8#37 二 class#38 二 nameandtype out:ljava/io/printstream;#39 = classjava/lang/string#53/ java/lang/system#54:#55/#56/ java/io/printstr

9、eam/#41二 utf8foreach/foreachtest#42=utf8java/1ang/objcct#43=utf8java/util/list#44=utf8java/util/iterator#45二 utf8add#46二 utf8(ljava/lang/object;)z#47=utf8iterator#48=utf8()ljava/uti1/lterator;#49=utf8hasnext#40 二 nameandtype#57:#58printin:(ljava/lang/string; )v#50 二 utf8#51 二 utf8#52 = utf8#53 = utf

10、8#54 = utf8()zn ext()ljava/lang/objcct; java/lang/system out#55 二 utf8#56 二 utf8#57 = utf8#58 = utf8ljava/io/printstream; java/i o/printstream printin(ljava/lang/string;)vpublic foreach. foreachtest();flags: acc_publtccode:stack=l, locals=l, args_size=l 0: aload 01: invokespecial #1 java/lang/object

11、:() v4: returnlinenumbertable:line 6: 0/ methodpublic static void main(java. lang. string); flags: acc_public, acc_staticcode:stack二2, locals=4, args_size=l 0: new#2java/util/arraylist3: dup4: invokespecial #3 java/util/arraylist"init>": ()v7:8:/classmethod9: ldc#411: invokeinterface #5

12、,2/ string si/ tnterfacemethodjava/uti1/list. add:(ljava/lang/objcct;)z16: pop17: aloadl18: ldc#6/ string s220: invokeinterface #5,2/ tnterfacemethodjava/uti1/list. add:(ljava/lang/objcct;)zastore_l aload 125: pop26: aloadl27: invokeinterface #7,1java/uti1/list. iterator:()ljava/uti1/tterator;32:33:

13、/interfacemethodastorc_2aload_234: invokeinterface #&1java/uti1/1terator. hasnext:()z39: ifeq42:43:62/interfacemethodaload_2invokeinterface #9,1/java/util/iterator. next:()ljava/lang/object;48: checkcastjava/1ang/stri ng51: dstore_352: getstaticinterfacemethod#10/class#11 java/lang/system. out:l

14、java/io/printstream;55: aload 3/field56: invokevirtual #12/ methodjava/io/printstream. printin:(ljava/lang/string;) v59: goto3362: returnlincnumbcrtablc:line 100line 118line 1217line 14261ine 1652line 1759line 1862stackmaptable: numberofentries = 2 frametype 二 253 /* append */offset_delta 二 33 local

15、s = class java/util/list, class java/util/itcrator frame_type = 250 /* chop */offsetdelta = 28 反编译出來的内容很多,看不懂也没关系,关键看到iterator这个标志,其实 在对有实现itcrablc接口的对象采用foreach语法糖的话,编译器会将这个for 关键字转化为对目标的迭代器使用。上面的代码会被转化为如下的代码:package foreach;import java.util. arraylist;import java.util. list;public class foreachtes

16、t编译器会对没有显示构造函数的类添加一个默认的构造函数,这个过程是 在语义分析邙介段完成的public foreachtest()super ();public static void main(string args)list<string> 1 ist 二 new arraylisto();list, add ("si");list, add(z,s2,z);for (java. util. iterator i$ = list, iterator () ; i$. hasnext ();)string s = (string) i$. next();sys

17、tem, out. println(s);注:如果耍想使fl己fl定义的类可以采用fomach语法糖就必须实 现 iterable 接口。细心的朋友可能会注意到,java中的数组也可以采用for each的语法糖,但是 数组并没有实现iterable接口呀。下面再举一个例子:package forcach;public class foreachtest2public static void main(string args)string arr = for(string s:arr)system, out. println(s);反编译结果:classfilc /d:/workspacc_j

18、cc/javatcst/src/forcach/forcachtcst2. class last modified 2016-2-25; size 581 bytesmd5 checksum 51656b3d3812c5ae3977fffd897a3441compiled from /zforeachtest2. javapublic class foreach. foreachtest2sourccfilc: /,forcachtcst2 java,zminor version: 0major version: 51flags: acc_public, acc_super#1 = metho

19、dref#8. #19/java/lang/object.nit>:()v#2 二 class#20/ java/lang/string#3 = string#21/ si#4 二 string#22/ s2#5 = fieldref#23. #24/java/lang/system out:ljava/io/printstream;#6 = methodref#25.#26/java/io/printstream. println: (ijeivei/lang/string;)v#7 = class#27/ forcach/forcachtcst2#8 = class#28/ java

20、/lang/object#9 = utf8<init>#10 二 utf8()v#11 二 utf8code#12 = utf8lincnumbcrtab1c#13 = utf8main#14 = utf8(ljava/lang/string;)v#15 二 utf8stackmaptable#16 二 class#29/" ljava/lang/string;#17 = utf8sourccfilc#18 = utf8foreachtest2java#19 = nameandtype#9:#10/:()v#20 二 utf8java/lang/string#21 二 u

21、tf8si#22 = utf8s2#23 = class#30/ java/lang/system#24 二 nameandtype#31:#32/out:ljava/io/printstream;#25 二 class#33/ java/io/pri ntstream#26 = nameandtype#34:#35/printin: (ljava/lang/string;)v#27 = utf8foreach/foreachtest2#28 二 utf8java/lang/object#29 二 utf8ljava/lang/stri ng;#30 = utf8java/1 emg/syst

22、em#31 = utf8outconstant pool:#32 二#33 二#34 二#35 =utf8utf8utf8utf8ljava/io/printstream; java/io/printstream printin(ljava/lang/string;)vpublic foreach. foreachtest2(); flags: acc_publiccode:stack二1, locals二1, args_size二1 0: aloado1: invokcspccial #1 java/lang/object.() v4: returnlinenumbertable:line

23、3: 0/ methodpublic static void meiin( java, la ng. s trin g); flags: acc_publ1c, acc_stat1cstack=4, locals=6,args_si ze=l0:iconst_21:anewarray#2java/lang/string4dup5iconst_06ldc#38aastore9dup10iconst_l11ldc#413aastore14astore_l15aloadl16astore_217aload_218arraylength19istore_320iconsto21istore423i l

24、oad425iload_326if_icmpge4929aload_230iload432aaload33astorc535getstatic#5java/lang/system. out:ljava/io/printstream38:aload5code:/ class/ string si/ string s2/ field40: invokevirtual #6/ methodjava/io/printstream. printin: (ljava/lang/string;)v43: iinc4, 146: goto2349: rcturnlinenumbertable:line 7:

25、0line 9: 15line 11: 35line 9: 43line 13: 49stackmaptable: number_of_entries = 2 frametype = 255 /* fullframe */ offsetdelta 二 23 locals 二class ljava/1 ang/string;class /zljava/lang/string;", class ,zljava/lang/string;", int, int stack =frametype = 248 /* chop */offsetdelta 二 25看不懂?同样没关系这里可

26、以注意到数组的foreach语法糖并没有采用 iterable实现转换。如上面的信息只是涉及一些压栈出站的内容。真止的解析 结果如下所示:package foreach;public class foreachtest2public 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); 可以看

27、到对于数组而言,其实就是转换为普通的遍历而已; 关于foreach语法糖的信息就这样结束了曠?显然没有! 对于实现randomaccess接口的集合比如arraylist,应当使用最普通的for循 环而不是foreach循环來遍j,所以第一个例了中有欠妥z处。首先看一下jdkl. 7中对randomaccess接口的定义:java, utilinterface randomaccessall known implementing classes:arraylist, attributelist, copyonwritearraylist, rolelist, roleunresolvedlis

28、t, stack, vectorpublic interface?randomaccessmarker interface used by list implemcntations 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 performanee when applied

29、 to either random or sequential access lists.the bost algorithms for manipulating random access lists (such as arraylist) can produce quadratic behavior when applied to sequential access lis ts (such as lin kedlist). generic list algor it hms are encouraged to check whether the given list is an inst

30、anceof this interface before applying an algorithm that would provide poor performanee 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 bet ween random and sequential access is often fuz

31、zy. for example, some list implementations provide asymptotically lineeir 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 typ

32、ical 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看不懂英文也没关系,我來解释一下最后一句加粗的话:实际经验表明,实现 randomacccss接口

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论