use*_*021 2 java constructor conflict variadic-functions
我和我的一个班级有问题.我正在使用"varargs"构造函数来获取未知数量的参数.
public Groupe(String...nom){
for(String item:nom){
this.nom.add(item.toLowerCase());
}
}
public Groupe(String nom){
String[] list =nom.split(",");
for(String s : list){
this.nom.add(s.toLowerCase());
}
}
Run Code Online (Sandbox Code Playgroud)
第一个构造函数被调用......这很好,但是当第二个构造函数只传递一个参数时会发生冲突.我只想在传递一个字符串时使用第二个构造函数,并且第一个if 2和更多参数.
我想要处理这个新的Groupe("Foo,Bar");
这就是我所说的.我怀疑"错误"来自那里
public void reserver(String...nom){
Groupe gr = new Groupe(nom);
passager.add(gr);
}
Run Code Online (Sandbox Code Playgroud)
我不传递字符串,而是传递Varargs(tab?)...
它应该没问题,null可以转换为String[]或者String:
public class Test {
public Test(String single) {
System.out.println("Single");
}
public Test(String... multiple) {
System.out.println("Multiple");
}
public static void main(String[] args) {
new Test("Foo"); // Single
new Test("Foo", "Bar"); // Multiple
new Test(); // Effectively multiple
// new Test(null); // Doesn't compile - ambiguous
new Test((String) null); // Single
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:既然你已经向我们展示了调用代码,那肯定是问题所在:
public void reserver(String...nom){
Groupe gr = new Groupe(nom);
passager.add(gr);
}
Run Code Online (Sandbox Code Playgroud)
这里的类型nom是String[]- 所以它总是会调用第一个构造函数.你有一个字符串数组 - 在什么情况下你想调用第二个构造函数?
老实说,鉴于两个构造函数的行为有很大不同,我实际上会将两个构造函数都设置为私有,并提供静态方法:
public static Groupe fromStringArray(String... nom)
public static Groupe fromCommaSeparatedString(String nom)
Run Code Online (Sandbox Code Playgroud)
那么在每种情况下你都会非常清楚你期待的是什么.