Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collection.addAll and generics

 
John Landon
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This is my code:

Given the facts that:
1. getSub1 returns collection of Sub1 that extends Sub class.
2. getSub2 returns collection of Sub2 that extends Sub class.

Why do I get a compilation error on the last line of the code?

Thanks.
 
Henry Wong
author
Marshal
Pie
Posts: 20880
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Landon:
Given the facts that:
1. getSub1 returns collection of Sub1 that extends Sub class.
2. getSub2 returns collection of Sub2 that extends Sub class.

Why do I get a compilation error on the last line of the code?




The declaration "Collection<? extends Sub> sub" does *not* mean a collection that takes anything that extends the Sub class type. It means a collection of some unknown class type that extends the Sub class type.

Since the class type is unknown, it can be any type that extends the Sub class type... and, it is impossible to add anything to the collection, as you can't confirm the type to match.

Henry
 
John Landon
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ohoh
so what do I do?
 
Henry Wong
author
Marshal
Pie
Posts: 20880
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by John Landon:
ohoh
so what do I do?


How about....



Henry
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or Collection<? super Sub>.

The rules:
- with "? super X" you can add anything that IS-A X but can only retrieve as Object without casts
- with "? extends X" you can add nothing but can retrieve as X without casts
- with "X" you can add anything that IS-A X and retrieve as X without casts
 
John Landon
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys!
It was really helpful
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic