Hi ranchers,
Sai Surya posted November 13, 2006 04:27 AM
? super AClass - Does this means that any super class of AClass?
? extends AClass - Does this means that any sub class of AClass?
yes, both of them. And including AClass itself (also for both of them).
There is another major difference between super and extends here.
? extends AClass only allows only to read in the collection. Trying to change (generic) values in the collection - for example add - will cause this funny capture of ? compiler error. I must be so, because you cannot add parents to a child list.
? super AClass does allow to change values or add things. This is because the type is at least AClass, you are allowed to add AClass objects to it (eg, the list can be <Parent> or <Master> in your example.
But you can only add objects that are of the type specified (or lower in hierarchy).
So in your example:
you can add parents and childs to "aList". Adding a master will not compile.
If you want a method that takes ArrayLists of Masters and subclasses, you could write
Then you could use this for ArrayLists of Master and subclasses and put the appropriate objects in.
But even calling the method right, e.g.
ArrayList<Master> masters = new ArrayList<Master>();
masters = g.add(masters , new Child() );
will cause a compiler warning (yet it compiles).
ArrayList<Parent> parents = new ArrayList<Parent>();
g.add(parents, new Master()); // no
however would not compile.
So we have our typesafety here.
I find it a bit tricky, all this generics stuff...
Yours,
Bu.