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>)
The method is not applicable because String
is an Object
but List<String>
is not a List<Object>
.
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));
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