I understand the difference between wildcard ? and type T
However unable to understand below code where in the method m3 I am passing a collection of type String.
Now in the method m3 when I try to add a String to the collection it does not allow me with an exception:
The method add(T) in the type List is not applicable for the arguments (String)
However in method m4 we are extracting an Element from the List and then adding it again.
<1> if T extends String then in method m3 why is it not allowing to add a String ?
<2> in method m4 when I am extracting an object from the List - and adding it again - this is allowed. Is it because when I extract the object is of type T and hence when adding it is allowed ?
Kind of strange behavior - I think I am getting a faint idea of why this happens but would be great to hear thoughts from others ?
package generics.wildcardVsT;
import java.util.ArrayList;
import java.util.List;
public class Ex1 {
public static void main(String[] args) {
System.out.println("hello");
List <String> list1 = new ArrayList<String>();
List <String> list2 = new ArrayList<String>();
List <String> list3 = new ArrayList<String>();
List <String> list4 = new ArrayList<String>();
list4.add("abc");
m1(list1);
m2(list2);
m3(list3);
m4(list4);
}
/** no compilation errors **/
public static void m1(List<String> list) {
list.add("abc");
}
/** this will not compile because of wildcard - this is understood **/
public static void m2(List<? extends String> list) {
list.add("abc");
}
/** this is not understood - why will this not compile ? **/
public static <T extends String>void m3(List<T> list) {
list.add("abc");
}
/** strangely this actually compiles ! **/
public static <T extends String>void m4(List<T> list) {
list.add(list.get(0));
}
}