本文介绍了使用枚举作为映射的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 enum
作为键和一个对象作为值.这是示例代码片段:
I want to use enum
as keys and a object as value. Here is the sample code snippet:
public class DistributorAuditSection implements Comparable<DistributorAuditSection>{
private Map questionComponentsMap;
public Map getQuestionComponentsMap(){
return questionComponentsMap;
}
public void setQuestionComponentsMap(Integer key, Object questionComponents){
if((questionComponentsMap == null) || (questionComponentsMap != null && questionComponentsMap.isEmpty())){
this.questionComponentsMap = new HashMap<Integer,Object>();
}
this.questionComponentsMap.put(key,questionComponents);
}
}
它现在是一个普通的哈希图,以整数键和对象作为值.现在我想把它改成Enummap
.这样我就可以使用 enum
键.我也不知道如何使用 Enummap
检索值.
It is now a normal hashmap with integer keys and and object as values. Now I want to change it to Enummap
. So that I can use the enum
keys. I also don't know how to retrieve the value using Enummap
.
推荐答案
与Map
原理相同,只需要声明enum
作为Key
code> 到 EnumMap
.
It the same principle as Map
Just Declare enum
and use it as Key
to EnumMap
.
public enum Color {
RED, YELLOW, GREEN
}
Map<Color, String> enumMap = new EnumMap<Color, String>(Color.class);
enumMap.put(Color.RED, "red");
String value = enumMap.get(Color.RED);
您可以在此处找到有关枚举
的更多信息
You can find more about Enums
here
这篇关于使用枚举作为映射的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!