Search code examples
javagenericsenumsenumset

Instantiate EnumSet from one of two types of Enum


I have these two Enums declared as such:

public enum EnumOne implements EnumInterface {
    SomethingHere,
    SomethingThere;
    public void someMethod () { }
}

public enum EnumTwo implements EnumInterface {
    SomethingOverYonder;
    public void someMethod () { }
}

As seen here, they both implement this Interface.

public Interface EnumInterface {
     someMethod();
}

I have a class defined here that contains an EnumSet that will get all the elements from either Enum1 or Enum2. That will be defined via a method that has an index as a parameter. Something like this:

public class SomeClass {
    private EnumSet someEnum;
    public void setEnumType (int index) {
        switch (index) {
        case 1:
            someEnum = EnumSet.allOf(EnumOne.class);
            break;
        case 2:
            someEnum = EnumTwo.allOf(EnumTwo.class);
            break;
        }
    }
}

Now, I know I have to use generics to accomplish this somehow, but i don't know how to do it exactly since I'm not familiar enough with it and I'm hoping you can enlighten me a bit.

Thanks in advance for your answers.


Solution

  • It is unclear what you are looking for, but if you just want someEnum to not be declared with a raw type, this works:

    public class SomeClass {
        private EnumSet<? extends EnumInterface> someEnum;
        public void setEnumType (int index) {
            switch (index) {
            case 1:
                someEnum = EnumSet.allOf(EnumOne.class);
                break;
            case 2:
                someEnum = EnumSet.allOf(EnumTwo.class);
                break;
            }
        }
    }