Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The method func(List<Object>) in the type is not applicable for the arguments (List<String>) [duplicate]

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>)

like image 268
ron reish Avatar asked Dec 03 '13 15:12

ron reish


2 Answers

The method is not applicable because String is an Object but List<String> is not a List<Object>.

like image 93
davioooh Avatar answered Oct 24 '22 07:10

davioooh


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));
like image 31
Ingo Avatar answered Oct 24 '22 06:10

Ingo