Oneb Oneb - 7 months ago 32
Java Question

Java - return type for enum values

Good day SO people. I have a problem regarding returning the inner enum values of my enum. I do not know which return type to use. I have tried googling and bumped into some solutions the uses generics however, I still have no luck. I do not know if my question has a solution or probably I did a bad design. So here goes, below
is my enum.

public enum KEYS
{
A("value"),
B("value"),
C("value");

public enum KEYS_GROUP_A
{
ITEM_A ("value"),
ITEM_B ("value"),
ITEM_C ("value");

private String value;
private KEYS_GROUP_A( String _value )
{
value = _value;
}

public String getVal()
{
return value;
}
}

public enum KEYS_GROUP_B
{
ITEM_A ("value"),
ITEM_B ("value"),
ITEM_C ("value");

private String value;
private KEYS_GROUP_B( String _value )
{
value = _value;
}

public String getVal()
{
return value;
}
}

public enum KEYS_GROUP_C
{
ITEM_A ("value"),
ITEM_B ("value"),
ITEM_C ("value");

private String value;
private KEYS_GROUP_C( String _value )
{
value = _value;
}

public String getVal()
{
return value;
}
}

private String value;
private PROPERTY_KEYS(String _value)
{
value = _value;
}

public String getVal()
{
return value;
}

public <?> getEnumValues(int x)
{
if ( 0 == x )
{
return KEYS.KEYS_GROUP_A.values();
}
else if ( 1 == x )
{
return KEYS.KEYS_GROUP_B.values();
}
else
{
return KEYS.KEYS_GROUP_C.values();
}
}
}


What I am trying to do is the
getEnumValues()
method. I have tried the return type
<T extends Enum<T>> T
but still an error occurs. Please tell if my design is bad or should not really be done. Please state some references. I'm willing to read and learn. Please shed some light! Thanks in advance!

Answer

The most specific type you can return is

public Enum<?>[] getEnumValues(int x)

You can return a more "useful" type if you define an interface like this:

interface HasVal { String getVal(); }

then make your enums all implement that interface, e.g.:

public enum KEYS_GROUP_A implements HasVal {
  // ...

  @Override public String getVal() { return value; }
}

Then you can return

public HasVal[] getEnumValues(int x)

and be able to invoke the getVal method on the instances:

for (HasVal val : getEnumValues(x)) {
  System.out.println(val.getVal());
}

You can't use:

public <T extends Enum<T>> T[] getEnumValues(int x)

because this isn't satisfiable for a general T. For instance, I could define:

enum Blah {}

and then try to invoke:

Blah[] blah = getEnumValues(1);

That wouldn't be type safe, because at least one (well, all, actually) of the code paths return a value which is not covariant with Blah[].