Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 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, 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?

like image 724
Amir Rachum Avatar asked Jun 29 '11 23:06

Amir Rachum


People also ask

Which class is a parent class to EnumSet?

It extends AbstractSet class and implements Set Interface in Java.

What is EnumSet noneOf?

EnumSet. noneOf(Class elementType ) method in Java is used to create a null set of the type elementType.

What is an EnumSet?

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.

Is EnumSet immutable?

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 .


2 Answers

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.

like image 177
Cameron Skinner Avatar answered Sep 20 '22 01:09

Cameron Skinner


Use Collections.unmodifiableSet:

return Collections.<Field>unmodifiableSet(EnumSet.allOf(Fields.class));

Pros:

  • No unsafe conversion cast: the operation is typesafe at runtime
  • The returned set is actually a Set<Field>, not a Set<? extends Field>
  • The set isn't copied, only wrapped
  • The returned set cannot be mutated

Cons:

  • The returned set cannot be mutated, but it wouldn't be safe to do so anyway.
like image 41
Daniel Pryden Avatar answered Sep 20 '22 01:09

Daniel Pryden