Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics and maps

 
Wendy Gibbons
Bartender
Posts: 1110
Eclipse IDE Oracle VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1110
Eclipse IDE Oracle VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
of course thank you, i am having a DOH!!! moment now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic