jQuery in Action, 3rd edition
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

Win a copy of REST with Spring (video course) this week in the Spring forum!
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: 4541

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: http://aspose.com/file-tools
subject: generics and maps
It's not a secret anymore!