Home > Java > javaTutorial > body text

How to fill an array with variable parameter list in java

WBOY
Release: 2023-04-24 22:13:13
forward
1082 people have browsed it

1. Description

Use a variable parameter list, no need to write array syntax explicitly, the compiler will fill the array. Can be applied to situations where the number or type of parameters is unknown.

2. Example

When the method parameter is a variable parameter list, you can pass a group of things as a list. If there is already a Array, this method can also accept it as a variadic argument list, in which case the compiler will not perform any conversion. At the same time, the variable parameter list can also pass no parameters, which is useful for scenarios with optional trailing parameters.

public class MyVarArgs {
    public static void main(String[] args) {
        printArray(1, 1.1F, 12.11);
        printArray("one", "two", "three", "four");
        printArray(new MyVarArgs(), new MyVarArgs());
        //数组作为参数
        Integer[] arr = new Integer[]{1,2,3,4};
        printArray((Object[]) arr);
        //参数为空
        printArray();
    }
    public static  void printArray(Object... args){
        for (Object obj : args){
            System.out.print(obj + " ");
        }
        System.out.println();
    }
}
/* 输出
1 1.1 12.11
one two three four
MyVarArgs@1b6d3586 MyVarArgs@4554617c
1 2 3 4
 
*/
Copy after login

The above is the detailed content of How to fill an array with variable parameter list in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template