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
source share
4 answers

You can return new HashSet<Field>(EnumSet.allOf(Fields.class));.

This will make it impossible for you to assign a type value to a type Set<User.Fields>variable Set<Field>.

Set<? extends Field> getFields(). Set<User.Field> .

+6

Collections.unmodifiableSet:

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

:

  • :
  • Set<Field>, Set<? extends Field>
  • ,

:

  • , .
+4

, , , 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
source

So I think a good solution. This is not exactly what you want, but close enough

import java.util.EnumSet;
import java.util.Set;

public class User {
    enum Fields implements Field {
        USERNAME,
        PASSWORD;
    }

    Set< ? extends Field> getFieldSet() {
        return EnumSet.allOf(Fields.class);
    }
}
0
source

All Articles