Question

I am trying to create an EnumSet array (using Eclipse).

Version 1:

EnumSet mySet[] = new EnumSet[3];

This works, but I get a warning: "EnumSet is a raw type. References to generic type EnumSet should be parameterized".

Version 2 as suggested:

EnumSet<MyEnum> mySet[] = new EnumSet[3];

Again a warning: "Type safety: The expression of type EnumSet[] needs unchecked conversion to conform to EnumSet[]"

Version 3 as suggested:

EnumSet<MyEnum> mySet[] = new EnumSet<MyEnum>[3];

Now I get an error! "Cannot create a generic array of EnumSet"

What should I do? Will a not parameterized EnumSet have performance issues?

Was it helpful?

Solution

You cannot create an array of concrete parameterized type, because it is not type safe. The reason being, the concrete parameterized type are not reified, whereas arrays are reified entity.

You can however create an array of raw type, or unbounded wildcard type:

EnumSet<?> mySet[] = new EnumSet<?>[3];

The reason this works is because rawtypes and unbounded wildcard types are reified. So, it's typesafe to create an array with such component type.

By reified, we mean the type information is available at runtime. This is not true with concrete parameterized type, because the type information is lost as a process of type erasure. However, for raw types, there is no type at all that can be lost. Same is true for <?> types. Since EnumSet<?> is a supertype of all instantiation of generic type EnumSet<T>, so there is no specific type information about EnumSet<?> at compile time that can be lost at runtime.

Another option is to simply create a list. This is far more better than mixing arrays with generic types:

List<EnumSet<MyEnum>> mySets = new ArrayList<>();

OTHER TIPS

Answer by Rohit Jain is correct, only I would like to add extended example. It uses casting for initialization.

Definition:

public enum CellState {
  MINE_EMPTY,MINE_NEAR_1,MINE_NEAR_2,MINE_NEAR_3,MINE_NEAR_4,MINE_NEAR_5,MINE_NEAR_6,
  MINE_NEAR_7, MINE_NEAR_8,MINE,CLICK_OPEN, CLICK_MARK;

  public static EnumSet<CellState> ALL_OPTS = EnumSet.allOf(CellState.class);
  public static EnumSet<CellState> NOT_MINE = EnumSet.of(MINE_EMPTY,MINE_NEAR_1,MINE_NEAR_2,MINE_NEAR_3,MINE_NEAR_4,MINE_NEAR_5,MINE_NEAR_6,
        MINE_NEAR_7, MINE_NEAR_8); 
}

}

Declaration:

  public EnumSet<CellState>[][] minefield; // 2-dimensional array

Initialization (casting needed):

minefield = (EnumSet<CellState>[][]) new EnumSet<?>[width][height];
for (int y = 0; y < height; y++) {
  for (int x = 0; x < width; x++) {
    minefield[x][y] = EnumSet.allOf(CellState.class);
  }
}

Usage:

if (!minefield[x][y].contains(CellState.MINE)) {
      minefield[x][y].add(minesNear(x, y));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top