问题
I have tried both these pieces of code but I am getting errors for both. Attached below are both pieces and both errors that I am getting. I would appreciate any insight as to why this is happening.
Example 1
static List<String> list = new ArrayList<String>();
public static void main(String[] args) {
func(list);
}
private static void func(List<Object> lst) {
}
Error:
The method func(List<Object>) in the type is not applicable for the arguments (List<String>)
Example 2
static List<Object> list = new ArrayList<Object>();
public static void main(String[] args) {
func(list);
}
private static void func(List<String> lst) {
}
Error:
The method func(List<String>) in the type is not applicable for the arguments (List<Object>)
回答1:
The method is not applicable because String is an Object but List<String> is not a List<Object>.
回答2:
Why you can't pass a List<String> to a List<Object>:
void bong(List<Object> objs) {
objs.add ( new Integer(42) );
}
List<String> strings = Arrays.toList("foo", bar");
bong(strings); // not allowed because ... see next line
for (String s : strings) print(x.charAt(0));
This would be safe only if the method couldn't modify the passed list. Unfortunatly, most Java classes are mutable, and so are most Lists implementations.
Why you can't pass a List<Object> to a List<String>:
void bing(List<String> strings) {
for (String s : strings) print(x.charAt(0));
}
bing(Arrays.toList((Object)1,(Object)2,(Object)3));
回答3:
static List<Object> list = new ArrayList<Object>();
public static void main(String[] args) {
func(list);
}
private static void func(List<Object> lst) {
}
This should work with the right imports (java util).
You can't supply List<Object> to a method with the parameter List<String>. It will only work with the same type parameters.
回答4:
You should basically understand the purpose of Generics and how it works:
List<String> list = new ArrayList<String>();
means that this list can only contain list of strings, and it can only be passed to methods that accepts the argument of type List<String>. And you can not substitute it for List <Object>.
In order to make the function more generic you can use:
function (List<?> list) {
//body
}
来源:https://stackoverflow.com/questions/20355809/the-method-funclistobject-in-the-type-is-not-applicable-for-the-arguments-l