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:
toString()
of Question
so it prints out "firstQuestion"
, but the actual value will still be QUESTION_FIRST
Map
to a Map<String, Integer>
, so map.put(QUESTION_FIRST.getValue(), 1);
will work"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.