Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Enum implementing interfaces with generic parameters

807580Dec 31 2009 — edited Dec 31 2009
The example code below is a condensed and simplified version of a construct containing an enum implementing an interface that uses generics. But it is not exactly what I want. First the code, then the question.
import java.util.Map;

interface Mapper<C extends Enum<C>, V> {
  V mapYourself(Map<C,V> map);
}
enum MyEnum implements Mapper<MyEnum,String> {
  EINS, ZWEI, DREI;
  
  public String mapYourself(Map<MyEnum,String> map) {
    return map.get(this);
  }
}
The idea is that an enum value gets a map, finds itself in the map and returns whatever the map has available for it. The code above compiles, but in fact it should work with just about any kind of map result, not just String. What I really would like to have, is that the result type is kept unspecified. I cannot do
enum MyEnum<V> implements Mapper<MyEnum,V> {...}
because Enums don't take generic arguments.

Ok, so I change the code to put the result generic parameter directly in front of the method, like this:
import java.util.Map;

interface Mapper<C extends Enum<C>> {
  <V> V mapYourself(Map<C,V> map);
}
enum MyEnum implements Mapper<MyEnum> {
  EINS, ZWEI, DREI;
  
  public <X> X mapYourself(Map<MyEnum,X> map) {
    return map.get(this);
  }
}
Not bad. But wait, I still would like to also have enums implementing a Mapper, but, please, only with a well defined value type of the map, e.g. String, because I would like the mapYourself to return a String. This does not work:
  public String mapYourself(Map<MyEnum,String> map) {
    return map.get(this)+this.toString();
  }
because this does not implement the method from the Mapper interface.

So it seems there is no way to define the Mapper such that both cases of enums can be covered:
a) enums that map to whatever the map provides
b) enums that need to know the value type of the map in order to manipulate it before returning it?

Am I missing something?
Harald.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 28 2010
Added on Dec 31 2009
1 comment
1,635 views