Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics question

 
Leroy J Brown
Ranch Hand
Posts: 71
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a bit of confusion about generics. I supposed simply for awesomeness sake that the below would be valid.



It seems to me that if the compiler knows that String extends Object it should allow me to "cast" a parametrized object to an object parametrized with the original's superclass in a similar vein to how we use polymorphism to hide implementation details from certain parts of our code:



I just want my method to say that it will take a HashMap who's parameters are, or are subtypes of, classes x and y. Is there a way to do this?

Thanks much
 
Brian Legg
Ranch Hand
Posts: 488
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can do what you are wanting to do. Do a search on "Generics with wildcards" as there is a lot of information relating to what your talking about and I'm not going to write/post an entire book here. So I guess the short answer is just, Yes.
 
Leroy J Brown
Ranch Hand
Posts: 71
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems to me that if the compiler knows that String extends Object it should allow me to "cast" a parametrized object to an object parametrized with the original's superclass in a similar vein to how we use polymorphism to hide implementation details from ...



As Brian mentioned, the correct way to do this is to use wildcards.

However, to answer your question... Just because a String IS-A Object, doesn't mean a Hashmap<String, String> IS-A Hashmap<Object, Object>. Think about it. You can add StringBuffers, Applets, Sockets, heck, any Objects types to a Hashmap<Object, Object>. Can a Hashmap<String, String> do that?

Henry
 
Campbell Ritchie
Sheriff
Pie
Posts: 47274
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will find about generics and wildcards here; look for subtyping and wildcards.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic