1. 可变参数相当于传数组参数,参数为0相当于数组为空
2. 当可变参数方法重载的时候,如果实际传参为0个,编译将不通过(无法分辨调用的哪个方法)
package com.yjq.cn.initialize;
/**
* 可变参数
*/
public class VarArgsTest {
static void fc(int i, String... str) {
System.out.print("fc.args : [" + i + " ");
for(String s : str) {
System.out.print(s + " ");
}
System.out.println("]; args.length: " + str.length);
}
//重载1
static void f(Integer... args) {
System.out.print("first");
for(Integer i : args) {
System.out.print(" " + i);
}
System.out.println();
}
//重载2
static void f(Character... args) {
System.out.print("second");
for(Character c : args) {
System.out.print(" " + c);
}
System.out.println();
}
//重载3
static void f(Long... args) {
System.out.print("third");
for(Long l : args) {
System.out.print(" " + l);
}
System.out.println();
}
public static void main(String[] args) {
fc(1, "one");
fc(2, "two", "three");
//可变参数个数可以传0个
fc(0);
System.out.println("--------------------");
//重载的情况
f('a', 'b', 'c');
f(1);
f(2, 1);
f(0);
f(0L);
// f(); //此时编译报错 The method f(Integer[]) is ambiguous for the type VarArgsTest
}
}
//output
fc.args : [1 one ]; args.length: 1
fc.args : [2 two three ]; args.length: 2
fc.args : [0 ]; args.length: 0
--------------------
second a b c
first 1
first 2 1
first 0
third 0