5

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

davioooh
  • 23,742
  • 39
  • 159
  • 250
ron reish
  • 81
  • 1
  • 1
  • 5
  • Generics are not covariant! That is, `List` cannot be substituted with `List` or the other way around! – Vincent van der Weele Dec 03 '13 at 16:06
  • You can't make the second one functional with the same semantics. The first one should work if you declare your func as ```private static void func(List> lst)``` – Danstahr Dec 03 '13 at 16:07

4 Answers4

8

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

davioooh
  • 23,742
  • 39
  • 159
  • 250
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));
Ingo
  • 36,037
  • 5
  • 53
  • 100
0
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.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
0

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
} 
Smar
  • 8,109
  • 3
  • 36
  • 48
Santosh Joshi
  • 3,290
  • 5
  • 36
  • 49