How to add different enum values to a Set as uniqu

2019-06-14 19:04发布

问题:

How to prevent different enum values of same enum type from being added to a set?

For instance, I've made a Size enum:

public enum Size {
    SMALL, MEDIUM, LARGE;
}

and added two different values into a Set of that type of Enum:

public class AttributesTestDrive {
    public static void main(String[] args) {
        Set<Size> sizes = new TreeSet<>();
        sizes.add(Size.LARGE);
        sizes.add(Size.MEDIUM);
        sizes.stream().forEach(System.out::println);
    }
}

How to override boolean equals(Object obj) within Enum? Or what else would you do to solve this issue?

P.S. As I know enums are classes within Java.

回答1:

How about a map instead of a Set?

Map <Class,Attribute> attributes;

Should do the job. You could have one Size:

attributes.put(Size.class, Size.LARGE);

and if you put it into a class you could even do some magic on retrieval:

public <T> T get (T defaultValue) {
  if (attributes.containsKey (defaultValue.getClass ())) {
     return (T) attributes.get (defaultValue.getClass ());
   } else  {
     return defaultValue;
   }
}