Home  >  Article  >  Java  >  How to fill an array with variable parameter list in java

How to fill an array with variable parameter list in java

WBOY
WBOYforward
2023-04-24 22:13:131070browse

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
 
*/

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!

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