Cannot convert fom enum to interface it implements

I'm in Java 7 and I have the following enum:

public enum BooleanEnum implements StringRepresentable{
    YES {
        @Override
        public String getStringRepresentation() {
            return "true";
        }
    },
    NO {
        @Override
        public String getStringRepresentation() {
            return "false";
        }
    };
    public abstract String getStringRepresentation();
}

Now I have the method:

List<StringRepresentable> getValues(){
    return Arrays.asList(BooleanEnum.values()); //Type mismatch: 
                  //cannot convert from List<BooleanEnum> to List<StringRepresentable>
}

What's wrong with that enum? It implements the interface, therefore the code should have compiled fine.

Jon Skeet
people
quotationmark

It implements the interface, therefore the code should have compiled fine.

No, because the type argument is being inferred as BooleanEnum - and a List<BooleanEnum> isn't a List<StringRepresentation>... you can add instances of other StringRepresentation implementations to the latter.

Four possible options:

  • Specify that you're returning a list of some subclass of StringRepresentation:

    List<? extends StringRepresentation> get Values() {
        // Implementation as before
    }
    
  • Specify the type argument:

    return Arrays.<StringRepresentation>asList(BooleanEnum.values());
    
  • Use an intermediate variable for clarity:

    StringRepresentation[] array = BooleanEnum.values();
    return Arrays.asList(array);
    
  • Don't return a List<StringRepresentation> at all; return an Iterable<StringRepresentation> at which point you can use EnumSet instead:

    Iterable<? extends StringRepresentable> getValues() {
        return EnumSet.allOf(BooleanEnum.class);
    }
    

people

See more on this question at Stackoverflow