aspose file tools*
The moose likes Beginning Java and the fly likes Generics question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics question" Watch "Generics question" New topic
Author

Generics question

Leroy J Brown
Ranch Hand

Joined: Dec 02, 2007
Posts: 71
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

Joined: Nov 07, 2008
Posts: 488
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.


SCJA
~Currently preparing for SCJP6
Leroy J Brown
Ranch Hand

Joined: Dec 02, 2007
Posts: 71
Thanks!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39415
    
  28
You will find about generics and wildcards here; look for subtyping and wildcards.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics question