The following code is a way to implement a variable parameter list.
public static void printAry(Object[] objs){ for(Object obj:objs){ System.out.print(obj+" "); } System.out.println(); } public static void main(String[] args) { printAry(new Object[]{1,2,3,4,5}); printAry(new Object[]{"ni","hao"}); }
Output result:
In this way, any type and number of parameters can be passed into the function. However, the above method is a relatively outdated method. After Java SE5 came out, a more convenient way was provided.
The code is as follows:
public static void printAry(Object... objs){ for(Object obj:objs){ System.out.print(obj+" "); } System.out.println(); } public static void main(String[] args) { printAry(1,2,3,4,5); printAry("ni","hao"); //无需显性的创建数组,由编译器自动填充。 printAry(new Object[]{"ni","hao"}); //也可传入数组。 printAry(); //可为空 printAry(new Integer(1),new Float(2));//可传不同类型的参数 }
Result:
The following code is a way to implement a variable parameter list.
public static void printAry(Object[] objs){ for(Object obj:objs){ System.out.print(obj+" "); } System.out.println(); } public static void main(String[] args) { printAry(new Object[]{1,2,3,4,5}); printAry(new Object[]{"ni","hao"}); }
Output result:
In this way, any type and number of parameters can be passed into the function. However, the above method is a relatively outdated method. After Java SE5 came out, a more convenient way was provided.
The code is as follows:
public static void printAry(Object... objs){ for(Object obj:objs){ System.out.print(obj+" "); } System.out.println(); } public static void main(String[] args) { printAry(1,2,3,4,5); printAry("ni","hao"); //无需显性的创建数组,由编译器自动填充。 printAry(new Object[]{"ni","hao"}); //也可传入数组。 printAry(); //可为空 printAry(new Integer(1),new Float(2));//可传不同类型的参数 }
Result:
Related recommendations:
Detailed explanation of variable length parameter code in Java
Detailed explanation of the example code of variable parameters in java
Analysis of Java's variable-length parameter list and points to note when using it
The above is the detailed content of Java -- Detailed code explanation of variable parameter list. For more information, please follow other related articles on the PHP Chinese website!