• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics : defining their relationship in order to ovloard a method  RSS feed

 
James JVogt
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to do something like:



but with generics:



of course the compiler complains that both puts have the same erasure and thus signature. Is something like this possible in Java? I would rather not make two methods "putT1(...)" "putT2(...)" since that would confuse things. Overloading by return type would also be great (for get() methods)... but I am pretty sure that is impossible in Java.
(I need this "double map" to ensure that the maps vary together in a specific way when one or the other is changed).
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you could try it as a generic method...



This way, you can support both types without using overloading... unfortunately, the issue here is that you can't limit it to only two types.

Henry
 
James JVogt
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That actually won't work either since you can't determine what type you got (at runtime) and then put that type the appropriate map. I.e., I can't do



but I found that my request is impossible in Java due to generics being implemented via erasure.

Well I suppose I could have the user pass in two class objects to the constructor... and compare the classes of the passed in objects against those class objects.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That actually won't work either since you can't determine what type you got (at runtime) and then put that type the appropriate map. I.e., I can't do


Hmmm.... you're absolutely correct. Without the instanceof operator, it isn't possible to determine the type. I figured out a way of avoiding the need for the operator -- by using maps of maps.... but even in that case, I couldn't avoid a typecast.

And regardless, this doesn't solve your problem of restricting it to only two types.

Anyway, in case you are interested.... here is my (somewhat broken) solution...



Henry
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:

That should be

This still allows you to put HashMap instances, but should you want to change you can turn it into a TreeSet or LinkedHashMap by only changing line 9 of your original code.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!