如何将不同的枚举值添加到集合作为唯一实体? [英] How to add different enum values to a Set as unique entities?

查看:124
本文介绍了如何将不同的枚举值添加到集合作为唯一实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止将不同的枚举类型的枚举值添加到一个集合?

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;
   }
}

这篇关于如何将不同的枚举值添加到集合作为唯一实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆