aspose file tools*
The moose likes Beginning Java and the fly likes Collection.addAll and generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collection.addAll and generics" Watch "Collection.addAll and generics" New topic
Author

Collection.addAll and generics

John Landon
Ranch Hand

Joined: Sep 25, 2008
Posts: 227
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: 19064
    
  40

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: 227
ohoh
so what do I do?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19064
    
  40

Originally posted by John Landon:
ohoh
so what do I do?


How about....



Henry
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19784
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
John Landon
Ranch Hand

Joined: Sep 25, 2008
Posts: 227
Thanks Guys!
It was really helpful
 
 
subject: Collection.addAll and generics