File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Generic Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generic Problem" Watch "Generic Problem" New topic

Generic Problem

peter tong
Ranch Hand

Joined: Mar 15, 2008
Posts: 245
assume there is a class called Main

when I write
Main main1 = new Main();
List<? extends Main> lm = new ArrayList<Main>();
lm.add(0, main1);

there is compile error on the statement
lm.add(0, main1);

what is the problem?
what can be added in lm?
Charles Lyons
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
So you know that List<? extends Main> means "this List is of some generic type which is Main or a subclass of it" - so that means it could be List<Main> or List<Sub> (where Sub extends Main) etc. Okay?

So now you want to add an instance of Main into the List. But as identified previously, the actual list might be List<Sub> (Sub any subclass of Main), and a Main isn't a Sub is it (the converse is true: a Sub is a Main)? So if you use <? extends Main>, you can't actually add anything into the list ever - because we just don't know what the list type actually is (no lower bound - unlike using <? super Sub>, when we would be able to put Sub or any of its subclasses into the list, but not Main or Object etc.).

The only case where this doesn't hold is if Main is final - since then it can have no subclasses, so <? extends Main> just means <Main>.

Note that using <? extends Main> gives us that upper bound on the type so when invoking get(0) for example, it will return an instance of type Main. This is primarily the usefulness of <? extends Main> - as an argument to a method where you will only want to retrieve objects from the list and know they are Main or a subclass.

If you want to put Main objects into a list but don't care about what generic type the list actually is, you use List<? super Main>. Now it could be List<Main>, List<SuperMain> (SuperMain a superclass of Main), List<Object> etc. All of those can contain Main objects, so the add() will succeed for a Main instance (or any subclass). However, this time calling get(0) we don't know an upper bound on the type - but since the widest possible type for any object is Object, it will just return an Object.

Charles Lyons (SCJP 1.4, April 2003; SCJP 5, Dec 2006; SCWCD 1.4b, April 2004)
Author of OCEJWCD Study Companion for Oracle Exam 1Z0-899 (ISBN 0955160340 / Amazon Amazon UK )
I agree. Here's the link:
subject: Generic Problem
It's not a secret anymore!