I am really not able to understand that why I get compilation error when in first case while works fine in second case.
public class GenericsTest3 {
public static <W> void main(String[] args) {
List<W> l1 = new ArrayList<String>(); // compilation error: Type mismatch: cannot convert from ArrayList<String> to List<W>
doSomething1(new ArrayList<String>()); // works fine
}
public static <L> L doSomething1(List<L> list) {
list.get(0);
list.add(list.get(0));
return list.get(1);
}
}
In my understand in both the cases List is defined of type parameter T/W, so why parameterized type new ArrayList<String>()
fails in one case while passes in other case.
CodePudding user response:
List<W> l1 = new ArrayList<String>();
Issue here is, that you declare a variable l1 for a List of type W items, but then you assign an (Array)List of type String to it. This is only acceptable, if W is also String.
You can just use W as type argument for the ArrayList or remove type argument from it.
List<W> l1 = new ArrayList<>();
Regarding your next question:
doSomething1(new ArrayList<String>());
Here you simply create a new ArrayList of type String and pass it as argument to doSomething1. At doSomething1, type argument L will therefore be String.
CodePudding user response:
case 1 :
List<W> l1 = new ArrayList<String>();
You are telling java that create a generic list and in the same declaration you are specifying the data type as String. So compiler is confused what to do.
Case 2 :
<L> L doSomething1(List<L> list) method
In this case java knows that generic list is input . All the action done on List interface. So compiles.