• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics doubt

 
Krzysztof Koziol
Ranch Hand
Posts: 133
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Justyna Wozniak
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So why is it only safe to add Strings to a List<? super String> ?

Thanks,
Justyna W.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic