如何将不同的枚举值添加到集合作为唯一实体?
问题描述:
如何防止将不同的枚举类型的枚举值添加到一个集合?
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;
}
,并将两种不同的值添加到这种类型的枚举集合中: p>
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);
}
}
如何覆盖 boolean equals (Object obj)
在Enum?或者还有什么可以解决这个问题?
How to override boolean equals(Object obj)
within Enum? Or what else would you do to solve this issue?
如我所知,枚举是Java中的类。
P.S. As I know enums are classes within Java.
答
地图而不是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;
}
}