Java syntax sugar 1: variable length parameters and the Foreach Loop principle

Source: Internet
Author: User
Tags iterable

Grammar Sugar

The next few articles to open a Java syntax Sugar series, so first of all to talk about what is the syntax of sugar. Grammar sugar is a kind of code that almost every language has provided to facilitate the programmer to develop the syntax, it is only a compiler implementation of a few tricks, during compilation in a specific bytecode or specific way to do some of these syntax, developers can directly and conveniently use. Although these syntactic sugars do not provide substantial functional improvements, they can improve performance, improve syntax rigor, or reduce the chance of coding errors. Java provides users with a large number of syntactic sugars, such as generics, auto-boxing, auto-unpacking, foreach loops, variable-length parameters, inner classes, enumeration classes, assertions (asserts), and so on.

Variable length parameters

Let's start with the variable length parameter and look at the code:

void Main (string[] args) {    print ("111", "222", "333");}    void for(int i = 0; i < strs.length; i++) {System.out.println (strs[i]);}}    

The parameters of the print method mean that the number of strings passed in is variable , and look at the result of the code running:

000111222333

I successfully traversed the input parameters in the form of an array traversal, indicating two problems:

1, you can use the way to iterate through the array of variable parameters

2, variable parameters are implemented using arrays

In that case, I can actually write the main function as well:

String[] STRs = {"$", "111", "222", "333"};p rint (STRs);

Well, what if you just pass in an array? The problem is, the array is to specify the length, in case I want to pass 2 string, next time I want to pass 3 string how to do?

Finally, note that the variable-length parameter must be the last parameter in the method parameter list and only one variable-length parameter in the method parameter list .

The Foreach Loop principle

This is how the Foreach loop used to be, touching me to study the principle of the Foreach loop is about two months ago, I wrote a ArrayList, want to use a Foreach loop to look at the effect of writing, the results reported a null pointer exception. This article writes about the principle of the Foreach loop, first look at this piece of code:

void Main (string[] args) {    new arraylist<string>(); List.add ("111"); List.add ("222"  For (String str:list) {System.out.println (str);}}     

Using a Foreach loop to traverse the list, the result is not said, all know. Take a look at how Java handles this foreach loop, Javap decompile:

F:\ Code \myeclipse\testarticle\bin\com\xrq\test21>javap-verbose Testmain.class

There is a lot of anti-compilation content, such as class information, symbolic reference, byte code information, to intercept a piece of information:

1PublicStaticvoidMain (java.lang.string[]);2Flags:acc_public, Acc_static3Code:4 stack=2, locals=4, args_size=15 0:New #16//Class Java/util/arraylist6 3: DUP7 4:invokespecial #18//Method java/util/arraylist. " <in8 it> ":() V9 7: Astore_110 8: Aload_19:LDC #19//String 11111:invokeinterface #21, 2//Interfacemethod java/util/list.Add: (ljava/lang/Object;) Z14 1615 17: aload_1< Span style= "color: #008080;" >16 18:ldc #27 // String 222 17 20:invokeinterface #21, 2 // Interfacemethod java/util/list. 18 add: (Ljava/lang/object;) Z 19 2520 26: Aload_121 27:invokeinterface #29, 1 // Interfacemethod java/util/list. 22 iterator: () Ljava/util/iterator               

It doesn't matter, new, DUP, invokespecial These are the instructions defined in the bytecode instruction table, and the virtual opportunity executes the specified C + + code according to these instructions to complete the function of each instruction. Key See 21, 22 These two lines is OK, see a iterator, so concluded: at compile time the compiler will automatically convert the use of the keyword to the use of the target iterator, this is the principle of the Foreach loop. In turn, we come to two more conclusions:

1, ArrayList can use the Foreach Loop traversal, because ArrayList all the list is collection sub-interface, and collection is iterable sub-interface, ArrayList of the parent class Abstractlist correctly implements the iterator method of the Iterable interface. I wrote it myself before. ArrayList directly to the null pointer exception with a foreach loop because I wrote it myself. ArrayList does not implement Iterable interface

2, any set, whether it is provided by the JDK or write their own, as long as you want to use the Foreach Loop traversal, you must correctly implement the Iterable interface

In practice, this is the iterator pattern in design mode in 23.

What about the array?

The above is finished, good understanding, but do not know whether people have doubts, at least I have a question: the array does not implement the Iterable interface Ah, why arrays can also be used in the Foreach Loop traversal it? First give a piece of code, and then decompile:

void Main (string[] args) {    int[] ints = {1,2,3,4,5 for(int i:ints) System.out.println (i);} 

Also decompile and look at the key information:

1 0: iconst_22 1:newarrayInt3 3: DUP4 4: Iconst_05 5: iconst_16 6: Iastore7 7: DUP8 8: iconst_19 9: iconst_210 10: Iastore11 11: Astore_112 12: Aload_113 13: DUP5 14:astore15 16: Arraylength4 17:istore17 19: Iconst_018 20: Istore_319 21:Goto 395 24:aload21 26: Iload_322 27: Iaload23 28: Istore_224 29:getstatic #16 // Field java/lang/system.out:ljav25 a/io/printstream; 32// Method java/io/printstream.prin28 tln: (I) V29 36:iinc 3, 130 39 : Iload_331 40:iload 4 42:IF_ICMPLT 2433: return     

This is the complete main function corresponding to the 45 bytecode directive, because this involves some compression stack, stack, push and so on some of the computer's original rational content and the knowledge of these bytecode instructions need some knowledge of C + +, so it is not explained. After a simple control of the bytecode instruction table, my personal understanding of these 45 bytecode is that Java converts the Foreach loop for the array to a circular reference to each of the arrays .

Java syntax sugar 1: variable length parameters and the Foreach Loop principle

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.