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:

 Public Static void Main (string[] args) {    print ("111", "222", "333");}      Public Static void print (String ... strs) {    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:

 Public Static void Main (string[] args) {    Listnew 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:

1    Public Static voidMain (java.lang.string[]);2 Flags:acc_public, Acc_static3 Code:4stack=2, locals=4, args_size=150:New#16//class Java/util/arraylist63: DUP74:invokespecial #18//Method java/util/arraylist. " <in8It> ":() V97: Astore_1Ten8: Aload_1 One9:LDC #19//String 111 A11:invokeinterface #21, 2//Interfacemethod java/util/list. -Add: (ljava/lang/Object;) Z -16: Pop the17: Aload_1 -18:LDC #27//String 222 -20:invokeinterface #21, 2//Interfacemethod java/util/list. -Add: (ljava/lang/Object;) Z +25: Pop -26: Aload_1 +27:invokeinterface #29, 1//Interfacemethod java/util/list. AIterator: () 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, The parent class of ArrayList 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:

 Public Static 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:

10: Iconst_221:newarrayint33: DUP44: Iconst_055: Iconst_166: Iastore77: DUP88: Iconst_199: Iconst_2Ten10: Iastore One11: Astore_1 A12: Aload_1 -13: DUP -14:astore 5 the16: Arraylength -17:istore 4 -19: Iconst_0 -20: Istore_3 +21st:Goto39 -24:aload 5 +26: Iload_3 A27: Iaload at28: istore_2 -29:getstatic #16//Field Java/lang/system.out:ljav -a/io/PrintStream; -32: Iload_2 -33:invokevirtual #22//Method Java/io/printstream.prin - tln: (I) V in36:iinc 3, 1 -39: Iload_3 to40:iload 4 +42:IF_ICMPLT 24 -45: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.