Convert from EnumSet <a> to set <b> when A inherits from B
The title pretty much explains the question. I have an interface method:
Set<Field> getFieldSet()
and I have a class Userthat looks something like this:
class User {
enum Fields implements Field {
USERNAME, PASSWORD;
...
}
...
}
Now I want to implement a method User getFieldSet(). The naive way seems simple return EnumSet.allOf(Fields.class), but I get the following error:
> Type mismatch: cannot convert from Set<User.Fields> to Set<Field>
Other than manually copying EnumSet to Set<Field>, is there a good way to do this?
+5
4 answers
, , , Set<Fields> Set<Field>. , Set<Fields> , :
Set<Field> fieldSet = user.getFieldSet(); //Returns an EnumSet<Fields>
fieldSet.add(new Field(){}); //Would compile, but would blow up at runtime,
//because the set can only contain Fields enum
//constants
- ( ) . :
Set<Field> getFieldSet() {
return Collections.unmodifiableSet(EnumSet.allOf(Fields.class));
}
, , (, , )
Set<Field> getFieldSet() {
return new HashSet(EnumSet.allOf(Fields.class));
}
+1