| Author |
Collection.addAll and generics
|
John Landon
Ranch Hand
Joined: Sep 25, 2008
Posts: 221
|
|
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
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
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
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
John Landon
Ranch Hand
Joined: Sep 25, 2008
Posts: 221
|
|
ohoh so what do I do?
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
Originally posted by John Landon: ohoh so what do I do?
How about.... Henry
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
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
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
John Landon
Ranch Hand
Joined: Sep 25, 2008
Posts: 221
|
|
Thanks Guys! It was really helpful
|
 |
 |
|
|
subject: Collection.addAll and generics
|
|
|