Michael D. Moffitt
Michael D. Moffitt

Reputation: 781

EnumMap and Java Generics

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).

Upvotes: 4

Views: 3867

Answers (2)

Pshemo
Pshemo

Reputation: 124225

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();

Upvotes: 4

Siva Kumar
Siva Kumar

Reputation: 2006

Please try like this

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

    EnumMap<T, Object> objs;
}

Upvotes: 1

Related Questions