![](/img/trans.png)
[英]How to use Switch and Enum Parameters (Not ENUM VALUE) in Java?
[英]How to use enum key value in java
我想在 java 11 中创建一个带有键值的枚举类我创建了一个这样的枚举
public enum status{
ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);
private final String key;
private final Integer value;
Status(String key, Integer value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public Integer getValue() {
return value;
}
}
当我做 Saison saison.getvalues() 我得到这样的问题
[
"ACTIVE",
"INACTIVE"
]
但我想变成这样
[
{
"Key": "Inactive",
"value":"2"
},
{
"Key": "Active",
"value":"1"
}
]
我怎样才能调用我的枚举 tio 得到这样的结果
没有什么可以阻止您返回包含key,value
对的映射条目。
enum Status {
ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);
private final String key;
private final int value;
Status(String key, int value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public int getValue() {
return value;
}
public Entry<String,Integer> getBoth() {
return new AbstractMap.SimpleEntry<>(key, value);
}
}
Entry<String,Integer> e = Status.ACTIVE.getBoth();
System.out.println("Key: = " + e.getKey());
System.out.println("Value: = " + e.getValue());
或打印条目的 toString() 值。
System.out.println(e);
印刷
Key: = Active
Value: = 1
Active=1
您还可以覆盖 Enum 的 toString 并执行类似的操作。
public String toString() {
return String.format("\"key\": \"%s\",%n\"value\": \"%s\"",
getKey(), getValue());
}
System.out.println(Status.ACTIVE);
印刷
"key": Active",
"value": "1"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.