如果我有一个 (Object...) 方法,为什么 Java 不会调用 (List
我有以下存储对象数组列表的类。
public class Test {
private List<Object[]> list = new ArrayList<Object[]>();
public void addList(Object... obj) {
list.add(obj);
}
public void addList(List<Object> lst) {
list.add(lst.toArray());
}
}
当我调用以下方法时,会调用重载方法 addList(Object... obj)
,但我希望调用 addList(List
public class Main {
public static void main(String[] args) {
Test testObj = new Test();
List<String> myStrings = new ArrayList<String>();
myStrings.add("string 1");
myStrings.add("string 2");
myStrings.add("string 3");
// The variable argument method is called but this is a list!
testObj.addList(myStrings);
}
}
I have the following class which stores a list of object arrays.
public class Test {
private List<Object[]> list = new ArrayList<Object[]>();
public void addList(Object... obj) {
list.add(obj);
}
public void addList(List<Object> lst) {
list.add(lst.toArray());
}
}
When I call the following, the overloaded method addList(Object... obj)
is called but I want the addList(List<Object> lst)
to be called. How can I do this?
public class Main {
public static void main(String[] args) {
Test testObj = new Test();
List<String> myStrings = new ArrayList<String>();
myStrings.add("string 1");
myStrings.add("string 2");
myStrings.add("string 3");
// The variable argument method is called but this is a list!
testObj.addList(myStrings);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将
List
Change
List<Object>
toList<?>
to capture lists of any type of object. I tried this and it printed "in List":这是Java泛型的问题。您不能将
List
分配给List
另请参阅:带有通用列表的 Java 参考分配
It's problem of Java Generic. You cannot assign
List<String>
toList<Object>
.See also: Java Reference assignment with generic lists
重写非可变参数方法的类型以使用通配符:
然后
List
将是参数类型的子类型。Rewrite the type of you non-variadic method to use a wildcard:
Then
List<String>
will be a subtype of the parameter type.List
不是List
List<String>
is not a subclass ofList<Object>
. So that overload will never be called, even if you remove the...
variant.将您的方法更改为
Change your method to