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

Win a copy of Java 8 in Action this week in the Java 8 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: 1106

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: 4244

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: 1106

of course thank you, i am having a DOH!!! moment now
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: generics and maps
Similar Threads
Sorting Maps
is object a list of string or only a string?
Map within a List
Vector within vector
Checkbox editor for JTable column