4

Suppose I have two enums:

enum MyEnum {A, B, C};
enum YourEnum {D, E, F};

and two very similar classes:

class MyRow {
  EnumMap<MyEnum, Object> map;
}

class YourRow {
  EnumMap<YourEnum, Object> map;
}

Is there a way to do something like this instead?

class Row<T implements Enum> {
  EnumMap<T, Object> map;
}

so that I can say Row<MyEnum> or Row<YourEnum>? I just don't want to have to define a new Row class for each of these specific enums (I have dozens).

5
  • what is Enum here T implements Enum Commented Aug 19, 2014 at 16:04
  • 1
    Map<Enum<?>, Object> whatever. Commented Aug 19, 2014 at 16:06
  • Where are you stuck? The class signature you posted compiles, and can be used as you describe, can it not? Commented Aug 19, 2014 at 16:07
  • 1
    What about class Row<T extends Enum<T>> ? Commented Aug 19, 2014 at 16:07
  • The "T extends Enum<T>" is the apparently the trick for this problem. Using implements gave me errors. Commented Aug 19, 2014 at 16:28

2 Answers 2

4

From your example it looks like you may be looking form something like

class Row<T extends Enum<T>> {
    EnumMap<T, Object> map;
}

You can use this class for instance like

Row<MyEnum> row = new Row<>();
row.map.put(MyEnum.A, "foo");//OK
//row.map.put(YourEnum.D, "bar");// Error, `put` from this reference 
                                 // is meant to handle `MyEnum`

inside the Row class, it doesn't seem to let me loop through values in the standard way:

for (T col : T.values())

T is generic type which is erased at runtime to Object and Object doesn't have values() method. Maybe you should consider including Class<T> field which would store information at runtime which exactly Enum you are using. This class has getEnumConstants() method which is similar to values() method.

So your code can look like

class Row<T extends Enum<T>> {
    EnumMap<T, Object> map;
    Class<T> enumType;

    public Row(Class<T> enumType){
        this.enumType = enumType;
    }

    void showEnums(){
        for (T col : enumType.getEnumConstants())
            System.out.println(col);
    }
}

and can be used for example this way

Row<MyEnum> row = new Row<>(MyEnum.class);
row.showEnums();
Sign up to request clarification or add additional context in comments.

1 Comment

A quick followup ... inside the Row class, it doesn't seem to let me loop through values in the standard way: for (T col : T.values()). Is there some way to achieve this?
1

Please try like this

public class Row<T extends Enum<T>> {

    EnumMap<T, Object> objs;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.