一、枚举类:
public enum Color{
RED(“红色”,1),GREEN(“绿色”,2),BLANK(“白色”,3),YELLOW(“黄色”,4);
//成员变量
private String name;
private int index;
//构造方法
private Color(String name,int index){
this.name = name;
this.index = index;
}
public static int takeIndex(String name){
for (Color color : Color.values()){
if (color.name.equals(name)){
return color.index;
}
}
return 0;
}
}
二、测试:
public class test {
public static void main(String[] args) {
int i = Color.takeIndex(“白色”);
System.out.println(i);
}
}
本文介绍了一种在Java中使用枚举类的方法,通过定义颜色枚举实例并提供静态方法来获取枚举值对应的索引。通过具体代码示例展示了如何创建枚举类型及其实现细节。
&spm=1001.2101.3001.5002&articleId=85072691&d=1&t=3&u=3f5337f28e494d43b216a7e0aecd00ea)
1万+

被折叠的 条评论
为什么被折叠?



