I am having a hard time to understand the concept of generics wild cards.
As per my understanding <?>
type unknown is introduced to resolve the co-variance not supported in generics and it should fit any type of collection and <?extends T>
means that you can have collection of types T
or the class which extends T.<?super T>
means you can have collection of types T
or super(s) of T
.
Please correct me, if the above is wrong.
When I try to write it like this:
import java.util.*;
public class Gclass {
static Gclass t;
public void write(List< ?super String > lw){
lw.add("b");
}
public void read(List< ? extends String> lr){
String s=lr.get(2);
System.out.println(s);
}
public static void main(String[] args) {
t=new Gclass();
List<String> l=new ArrayList<String>();
l.add("a");
l.add("");
System.out.println(l);
t.write(l);
System.out.println(l);
t.read(l);
System.out.println(l);
}
}
It works but my places of doubt are:
As per my understanding both (extends and super) includes the type declared, so in this particular case as my
List
is of typeString
. I could interchange the extends and super, but I get compilation error?In case of write
? super Object
is not working? It should work as it is super ofString
?I did not check for read as
String
can not be extended, but I think I'm also missing a concept here.
I've read all answers on SO related to this problem, but am still not able to have a good understanding about it.