File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

generics and maps

Wendy Gibbons

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

Joined: Apr 06, 2010
Posts: 4543

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

Joined: Oct 21, 2008
Posts: 1107

of course thank you, i am having a DOH!!! moment now
I agree. Here's the link:
subject: generics and maps
jQuery in Action, 3rd edition