wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics doubt" Watch "Generics doubt" New topic
Author

Generics doubt

Krzysztof Koziol
Ranch Hand

Joined: Nov 19, 2006
Posts: 133

Why the following code doesn't compile?

List < ? super String> list = new ArrayList <String>();
list.add(new Object());

Object is a super class for all clasess, right?

Regards


SCJP 5.0, SCWCD 5.0, SCBCD 5.0, SCEA/OCMJEA 5.0
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi cowboys,

Krzysztof Koziol posted November 19, 2006 03:15 AM

Object is a super class for all clasess, right?

Yes, but you list is not of type <Object> but of type <? super Strings>.

To a List<? super Strings> you can


1) assign all kinds of lists that are of type String or higher.
You assigned a new List<String> to it, you could have also said:
List <? super String> list = new ArrayList <Object>();

But even then, you could not add Objects to this list. Because it is only save to add Strings to a List<? super Strings> (or to add subtypes, but subclasses of String do not exist).
Because it is allowed (point 1) to also (as you did) assign Lists of type <String> to it, and you cannot add objects that are "higher" than String to a List<String>. So in brief, you can

2) add only types of type String to it.


And welcome to the Ranch, Krzysz!




Yours,
Bu.


all events occur in real time
Justyna Wozniak
Greenhorn

Joined: Oct 04, 2006
Posts: 14
So why is it only safe to add Strings to a List<? super String> ?

Thanks,
Justyna W.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi ranchers,

Justyna Wozniak posted November 19, 2006 02:14 PM
So why is it only safe to add Strings to a List<? super String> ?


OK, other example:

class A {}
class B extends A {}
class C extends B {}
class D extends C {}
class E extends D {}


and

List<? super C> myList;


What kind of parameterized ArrayLists you can assign to this list?

What is the most specific (regarding inheritance) type you can parameterize your list with?

What is the most unspecific type you can assign to this list which is parameterized most specifically?

Can you also add the type from the last question to a list that is parameterized with a more unspecific ("lower") type? - or with a more specific ("higher").


Yours,
Bu.
 
wood burning stoves
 
subject: Generics doubt
 
Similar Threads
Generics doubt (? super String)
Generic Question in JAVA Beat
Generics
Collections.binarySearch() problem
GENERICS