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);
}
}
Change List<Object>
to List<?>
to capture lists of any type of object. I tried this and it printed "in List":
import java.util.ArrayList;
import java.util.List;
public class Test {
private List<Object[]> list = new ArrayList<Object[]>();
public void addList(Object... obj) {
System.out.println("in object");
list.add(obj);
}
public void addList(List<?> lst) {
System.out.println("in List<?>");
list.add(lst.toArray());
}
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);
}
}
It's problem of Java Generic. You cannot assign List<String>
to List<Object>
.
See also: Java Reference assignment with generic lists
Rewrite the type of you non-variadic method to use a wildcard:
public void addList(List<?> lst) {
list.add(lst.toArray());
}
Then List<String>
will be a subtype of the parameter type.
List<String>
is not a subclass of List<Object>
. So that overload will never be called, even if you remove the ...
variant.
Change your method to
public void addList(List<?> lst) {
list.add(lst.toArray());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With