简体   繁体   中英

Set Enum constant values as hashmap key in java

I have below enum defined. I have declared a Hashmap with its key as enum. 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"

@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. You have three options:

  • Change the toString() of Question so it prints out "firstQuestion" , but the actual value will still be QUESTION_FIRST
  • Change the Map to a Map<String, Integer> , so map.put(QUESTION_FIRST.getValue(), 1); will work
  • Give up on your desire to have "firstQuestion" be the key in the map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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