How to add different enum values to a Set as uniqu

2019-06-14 18:08发布

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条回答
该账号已被封号
2楼-- · 2019-06-14 19:04

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;
   }
}
查看更多
登录 后发表回答