首页 > 编程语言 > 详细

Java switch 中如何使用枚举?

时间:2021-08-12 12:01:17      阅读:25      评论:0      收藏:0      [点我收藏+]

enum HobbyEnum{
SIGN("唱","SING"),
JUMP("跳","JUMP"),
RAP("Rap","RAP"),
OTHER("未知","OTHER");

private String word;
private String type;

HobbyEnum(String word, String type){
this.word = word;
this.type = type;
}

public String getWord() {
return word;
}

public void setWord(String word) {
this.word = word;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public static HobbyEnum getByType(String type){
for (HobbyEnum constants : values()) {
if (constants.getType().equalsIgnoreCase(type)) {
return constants;
}
}
return OTHER;
}
}

想使用switch去替换掉if-else,想到Hobby这个类里面的type属性正好是个枚举,就想用枚举去实现,结果发现这样是有问题的。

枚举类

public enum HobbyEnum{
SIGN("唱","SING"),
JUMP("跳","JUMP"),
RAP("Rap","RAP"),
OTHER("未知","OTHER");

private String word;
private String type;

HobbyEnum(String word, String type){
this.word = word;
this.type = type;
}

public String getWord() {
return word;
}

public void setWord(String word) {
this.word = word;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}
}

技术分享图片

 

 

 

解决方案

修改枚举类

新增一个静态方法,getByType()

enum HobbyEnum{
SIGN("唱","SING"),
JUMP("跳","JUMP"),
RAP("Rap","RAP"),
OTHER("未知","OTHER");

private String word;
private String type;

HobbyEnum(String word, String type){
this.word = word;
this.type = type;
}

public String getWord() {
return word;
}

public void setWord(String word) {
this.word = word;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public static HobbyEnum getByType(String type){
for (HobbyEnum constants : values()) {
if (constants.getType().equalsIgnoreCase(type)) {
return constants;
}
}
return OTHER;
}
}

技术分享图片

 

 

转载至 https://www.cnblogs.com/codeclock/p/12564924.html

Java switch 中如何使用枚举?

原文:https://www.cnblogs.com/zxy-come-on/p/15131504.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!