The title pretty much explains the question. I have an interface method:
Set<Field> getFieldSet()
and I have a class, User
which looks something like this
class User {
enum Fields implements Field {
USERNAME, PASSWORD;
...
}
...
}
Now I want to implement User
's getFieldSet()
method. The naive way seems to just 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 the EnumSet to Set<Field>
, is there a good way to do this?
It extends AbstractSet class and implements Set Interface in Java.
EnumSet. noneOf(Class elementType ) method in Java is used to create a null set of the type elementType.
An EnumSet is a specialized Set collection to work with enum classes. It implements the Set interface and extends from AbstractSet: Even though AbstractSet and AbstractCollection provide implementations for almost all the methods of the Set and Collection interfaces, EnumSet overrides most of them.
Yes EnumSet is modifiable. If you want to create an immutable EnumSet then go for immutableEnumSet. Returns an immutable set instance containing the given enum elements. Internally, the returned set will be backed by an EnumSet .
You could return new HashSet<Field>(EnumSet.allOf(Fields.class));
.
That will get around the fact that you can't assign a value of type Set<User.Fields>
to a variable of type Set<Field>
.
Alternatively, your interface could be Set<? extends Field> getFields()
instead. You can assign Set<User.Field>
to a capturing variable.
Use Collections.unmodifiableSet:
return Collections.<Field>unmodifiableSet(EnumSet.allOf(Fields.class));
Pros:
Set<Field>
, not a Set<? extends Field>
Cons:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With