This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes generics and maps Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "generics and maps" Watch "generics and maps" New topic
Author

generics and maps

Wendy Gibbons
Bartender

Joined: Oct 21, 2008
Posts: 1107

Why doesn't the compiler like this line?


but hashmap does implement Map (i double checked just incase i was going crazy)

but this works:
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4541
    
    8

When you assign generics like that, you have to match the generic type exactly.

Here's why it's not allowed like that. You've created a list that should only be able to accept HashMaps (probably not what you want, but let's pretend it is). But then you've assigned it to a reference that suggests it should be able to add any sort of Map. So the compiler would then allow you to add, say, a Hashtable. And because the generic types don't exist at runtime, there'd be no error. So you've lost the type-safety that you thought you had.

It's exactly the same reason that you can't go:

The second approach you've used is the correct one.
Wendy Gibbons
Bartender

Joined: Oct 21, 2008
Posts: 1107

of course thank you, i am having a DOH!!! moment now
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: generics and maps
 
jQuery in Action, 3rd edition