简体   繁体   English

将枚举常量值设置为 java 中的 hashmap 键

[英]Set Enum constant values as hashmap key in java

I have below enum defined.我在下面定义了枚举。 I have declared a Hashmap with its key as enum.我已经声明了一个 Hashmap,其密钥为枚举。 When I am trying to put enum constant value as key in hashmap, key is getting stored with "QUESTION_FIRST" while I want it to be "firstQuestion"当我尝试将枚举常量值作为 hashmap 中的键时,键将与“QUESTION_FIRST”一起存储,而我希望它是“firstQuestion”

@Getter
public enum Question {

    QUESTION_FIRST("firstQuestion"),
    QUESTION_SECOND("secondQuestion");

    private final String value;

    Question(String value){
        this.value = value;
    }

    public String getValue(){
        return value;
    }
}

public void testMethod(){
Map<Question, Integer> map = new HashMap<>();
map.put(QUESTION_FIRST.getValue(), 1);
}

A Map<Question, Integer> can only have QUESTION_FIRST as a key. Map<Question, Integer>只能将QUESTION_FIRST作为键。 You have three options:您有以下三种选择:

  • Change the toString() of Question so it prints out "firstQuestion" , but the actual value will still be QUESTION_FIRST更改QuestiontoString()以便它打印出"firstQuestion" ,但实际值仍将是QUESTION_FIRST
  • Change the Map to a Map<String, Integer> , so map.put(QUESTION_FIRST.getValue(), 1);Map更改为Map<String, Integer> ,因此map.put(QUESTION_FIRST.getValue(), 1); will work将工作
  • Give up on your desire to have "firstQuestion" be the key in the map.放弃让"firstQuestion"成为 map 中的关键的愿望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM