Home  >  Article  >  Java  >  What are variable length parameters in java? What is the principle of foreach loop?

What are variable length parameters in java? What is the principle of foreach loop?

青灯夜游
青灯夜游forward
2018-10-19 17:19:252176browse

The content of this article is to introduce what are variable length parameters in Java? What is the principle of foreach loop? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Syntax sugar

Syntactic sugar is a convenience that almost every language provides to some extent. The syntax for programmers to develop code is just some little tricks implemented by the # during compilation. Specific bytecode or specific methods are used to process these syntaxes, and developers can use them directly and conveniently. Although these syntax sugars will not provide substantial functional improvements, theymay improve performance, improve the rigor of syntax, or reduce the chance of coding errors . Java provides users with a lot of syntactic sugar, such as generics, autoboxing, autounboxing, foreach loops, variable length parameters, inner classes, enumeration classes, assertions, etc.

2. Variable length parameters

Let’s talk about variable length parameters first, look at a piece of code:

public static void main(String[] args)
{
    print("000", "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 incoming Strings is variable, take a look at the running results of the code:

000
111
222
333

I used array traversal The method successfully traversed the input parameters, which illustrates two problems:

1. You can use the method of traversing the array to traverse the variable length parameters

2. Variable parameters are implemented using arrays

In this case, I can actually write the main function like this, it is absolutely fine:

String[] strs = {"000", "111", "222", "333"};
print(strs);

Wouldn’t it be better to pass in an array directly? The problem is that the length of the array must be specified. What if I want to pass 2 Strings this time and 3 Strings next time?

Finally, please note that The variable length parameter must be used as the last parameter in the method parameter list and there can only be one variable length parameter in the method parameter list.

3. Principle of foreach loop

This is how the foreach loop was used before, which inspired me to study the principle of foreach loop. The reason is that about two months ago, I wrote an ArrayList myself. I wanted to use a foreach loop to traverse it to see the effect of writing, but a null pointer exception was reported. This article will write about the principle of foreach loop. First, take a look at this piece of code:

public static void main(String[] args)
{
    List<String> list = new ArrayList<String>();
    list.add("111");
    list.add("222");
    
    for (String str : list)
    {
        System.out.println(str);
    }
}

Use foreach loop to traverse this list. I won’t explain the result, everyone knows it. Take a look at how Java handles this foreach loop. Decompile it with javap:

F:\代码\MyEclipse\TestArticle\bin\com\xrq\test21>javap -verbose TestMain.class

There is a lot of decompiled content, including class information, symbol references, and bytecode information. A piece of information is intercepted:

public static void main(java.lang.String[]);
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=2, locals=4, args_size=1
         0: new           #16                 // class java/util/ArrayList
         3: dup
         4: invokespecial #18                 // Method java/util/ArrayList."<in
it>":()V
         7: astore_1
         8: aload_1
         9: ldc           #19                 // String 111
        11: invokeinterface #21,  2           // InterfaceMethod java/util/List.
add:(Ljava/lang/Object;)Z
        16: pop
        17: 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.
iterator:()Ljava/util/Iterator;

It doesn’t matter if you don’t understand it. New, dup, and invokespecial are originally instructions defined in the bytecode instruction table. The virtual machine executes the specified C code based on these instructions to complete the function of each instruction. The key is to see lines 21 and 22. I saw an iterator, so I came to the conclusion: The compiler will automatically compile for# during compilation. ##eachThe use of this keyword translates into # for the target ##Usage of iterator,This is the principle of foreach loop. Furthermore, we draw two more conclusions:

#1. The reason why ArrayList can be traversed using foreach loop is because all of ArrayList List is a sub-interface of Collection, and Collection is a sub-interface of

Iterable. AbstractList, the parent class of ArrayList, correctly implements the iterator method of the Iterable interface. Previously, the ArrayList I wrote directly reported a null pointer exception using a foreach loop because the ArrayList I wrote did not implement the Iterable interface

2、任何一个集合,无论是JDK提供的还是自己写的只要想使用foreach循环遍历,就必须正确地实现Iterable接口实际上,这种做法就是23中设计模式中的迭代器模式

数组呢?

上面的讲完了,好理解,但是不知道大家有没有疑问,至少我是有一个疑问的:数组并没有实现Iterable接口啊,为什么数组也可以用foreach循环遍历呢?先给一段代码,再反编译:

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

同样反编译一下,看一下关键的信息:

0: iconst_2
         1: newarray       int
         3: dup
         4: iconst_0
         5: iconst_1
         6: iastore
         7: dup
         8: iconst_1
         9: iconst_2
        10: iastore
        11: astore_1
        12: aload_1
        13: dup
        14: astore        5
        16: arraylength
        17: istore        4
        19: iconst_0
        20: istore_3
        21: goto          39
        24: aload         5
        26: iload_3
        27: iaload
        28: 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
        36: iinc          3, 1
        39: iload_3
        40: iload         4
        42: if_icmplt     24
        45: return

这是完整的这段main函数对应的45个字节码指令,因为这涉及一些压栈、出栈、推送等一些计算机原理性的内容且对于这些字节码指令的知识的理解需要一些C++的知识,所以就不解释了。简单对照字节码指令表之后,我个人对于这45个字节码的理解是Java将对于数组的foreach循环转换为对于这个数组每一个的循环引用

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。更多相关教程请访问Java视频教程java开发图文教程bootstrap视频教程

The above is the detailed content of What are variable length parameters in java? What is the principle of foreach loop?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete