猿问

列出具有唯一键作为对象或枚举的键值

问题

  • 我想要一个键值对的列表,例如HashMap或其他推荐。

  • 此列表应包含用于检索值的唯一键对象。

  • 键不应该是字符串,因为字符串不是唯一的,任何值都可以传递。

  • 此外,常量是有限的,并且也使用字符串的概念,因此不应考虑。

  • 例如,想要的是list[Color.Red] = “Red”。

  • 在此阶段,我创建了一个包含所有键的枚举。例如,枚举 Color{RED,BLUE} 然后将其添加到新的 HashMap 中。

  • 因此,检索颜色的唯一方法是使用枚举作为键列表[Color.RED]。

实现

public final static Map<Color, String> colors = new HashMap<>();

public final static enum Color{RED, BLUE;}

static

{

   colors.put(RED, "red");

   colors.put(BLUE, "blue");

}

public static string getColor(Color color)

{

   return colors.get(color);

}

需要帮助


Java中是否有一种类型的集合可以完成这项工作?如果不是,那么这样做的最佳做法是什么?


泛舟湖上清波郎朗
浏览 146回答 2
2回答

HUWWW

潜在解决方案在检查枚举及其可能性之后,有一种方法可以将值分配给枚举中的键,如下所示。创建一个新枚举并分配 Key,例如公共枚举 Color{RED;}。向其添加构造函数参数,例如公共枚举 Color{RED(“red”);}向枚举添加构造函数,例如公共枚举 Color{RED(“red”);Color(){}}在枚举中添加一个名为值的新字段,例如私有字符串值;public String getValue() {return value;}在枚举的构造函数中设置字段值,例如 Color(String value) {this.value = value;}Enum以这种方式工作,对于您添加的每个Key,它都会创建一个链接到Key的新实例字段 String值,然后它将使用您声明的构造函数来保存该值。全面实施public enum Color{&nbsp; &nbsp;//[PROP]&nbsp; &nbsp;RED("red"),&nbsp; &nbsp;GREEN("green"),&nbsp; &nbsp;BLUE("blue");&nbsp; &nbsp;private String value;&nbsp; &nbsp;public String getValue {return value;}&nbsp; &nbsp;//[BUILD]&nbsp; &nbsp;Color(String value) {this.value = value;}&nbsp; &nbsp;//[UTIL]&nbsp; &nbsp;Color[] getKeys() {return this.values;} //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.}如果我们想检索一个项目,我们只需执行Color.RED.value,这样只有现有的键返回想要的值。请注意,值不必是键的名称,但可以是完全不同的值。如果您有任何更简单的解决方案,而不会给解决方案带来更多复杂性,请发表评论。

叮当猫咪

这些键在所有地图中都是唯一的。添加重复的键,然后它将被覆盖。各种映射实现之间的差异涉及空键的可能性,迭代顺序和并发问题。示例:Map&nbsp;hm&nbsp;=&nbsp;new&nbsp;HashMap(); hm.put("1",&nbsp;new&nbsp;Integer(1)); hm.put("2",&nbsp;new&nbsp;Integer(2)); hm.put("3",&nbsp;new&nbsp;Integer(3)); hm.put("4",&nbsp;new&nbsp;Integer(4)); hm.put("1",&nbsp;new&nbsp;Integer(5));//&nbsp;value&nbsp;integer&nbsp;1&nbsp;is&nbsp;overwritten&nbsp;by&nbsp;5此外,Map键是通用的,你可以放你想要的,而不仅仅是字符串,示例:Map<Integer,&nbsp;String>&nbsp;hm&nbsp;=&nbsp;new&nbsp;HashMap<>(); hm.put(10,&nbsp;"1");
随时随地看视频慕课网APP

相关分类

Java
我要回答