This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics question

 
Leroy J Brown
Ranch Hand
Posts: 71
  • 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
  • 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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Henry Wong
author
Marshal
Pie
Posts: 20902
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 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
Posts: 48445
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will find about generics and wildcards here; look for subtyping and wildcards.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic