最近在学习Groovy,发现Groovy中的Switch case 比Java中的Switch case强大,于是了解了Java中的Switch case支持的数据类型是有限的,包括int,char,String 和enum四种类型。
之前写android代码的时候,前面3中经常用,但是第4种类型没有使用过,于是尝试使用枚举类型来学些Switch case,代码如下,做个记录:
1、先定一个枚举类型:
package com.lwd;
public enum LwdColor {
yello(0,"#0xff00ff00"),
green(1,"#0xff0000ff"),
blue(2,"#0xffffff00");
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
private String desc;
LwdColor(int value,String desc){
this.value = value;
this.desc = desc;
}
public static LwdColor getColorType(int type){
for(LwdColor lwdColors:LwdColor.values()){
if(lwdColors.getValue() == type){
return lwdColors;
}
}
return null;
}
}
枚举类中定义了3种颜色,分别是yello、green、blue,构造方法中定义的两个变量,分别是value和desc,value和desc分别对应枚举颜色中的key和value。 提供了一个静态方法,来根据传入的类型来获取对应的枚举值。
2、在Switch case中使用如下:
package com.lwd;
public class TestJava {
public static void main(String[] args){
LwdColor lwdColor = LwdColor.getColorType(0);
switch (lwdColor){
case yello:
System.out.println( lwdColor.getValue() + "的颜色值 == " + lwdColor.getDesc());
break;
}
}
}