可变参数用类型...定义,可变参数相当于数组类型:
class Group { private String[] names; public void setNames(String... names) { this.names = names; } public void setAges(int... names) { this.names = names; } }
上面的setNames()就定义了一个可变参数。调用时,可以这么写:
Group g = new Group(); g.setNames("Xiao Ming", "Xiao Hong", "Xiao Jun"); // 传入3个String g.setNames("Xiao Ming", "Xiao Hong"); // 传入2个String g.setNames("Xiao Ming"); // 传入1个String g.setNames(); // 传入0个String
完全可以把可变参数改写为String[]类型:
class Group { private String[] names; public void setNames(String[] names) { this.names = names; } }
但是,调用方需要自己先构造String[],比较麻烦。例如:
Group g = new Group(); g.setNames(new String[] {"Xiao Ming", "Xiao Hong", "Xiao Jun"}); // 传入1个String[]
另一个问题是,调用方可以传入null:
Group g = new Group(); g.setNames(null);