您的位置:首页 > 编程语言 > Java开发

JAVA中enum的常见用法

2013-07-14 14:22 393 查看
JAVA中enum的常见用法包括:定义并添加方法、switch、遍历、EnumSet、EnumMap

1.定义enum并添加或覆盖方法

public Interface Behaviour{
void print();
}
enum Color implements Behaviour{
RED("red",1),GREEN("green",2),BLUE("blue",3);	//注意这里有个分号

private String name;
private int index;
private Color(String name,int index){
this.name = name;
this.index = index;
}
public static String getName(int index){
for(Color color : Color.values()){
if(color.index == index)
return color.name;
}
return null;
}
public String toString(){			//覆写toString()方法
return this.index + ":" + this.name;
}
public String getInfo(){
return this.name;
}
}


①这个Color枚举类是个final class,不能被继承,它本身是继承自Enum;

②这些枚举值是Color对象,而且是static final修饰的;

③valueOf(String)方法,返回带指定名称的指定枚举类型的枚举常量。

2.switch和enum的遍历

public static void main(String[] args) {

Color c =  Color.valueOf("BLUE");
switch(c){
case RED:
System.out.println(c);
case BLUE:
System.out.println(c);
}

for(Color color : Color.values()){
System.out.println(color.toString());
}
}
switch其实是支持int基本类型,而因为byte,short,char可以向上转换为int,所以switch也支持它们,但long因为转换int会截断便不能支持。

3.EnumSet和EnumMap的用法

public static void main(String[] args) {
EnumSet<Color> es = EnumSet.allOf(Color.class);
for(Color color : es){
System.out.println(color);
}

EnumMap<Color,String> colorMap = new EnumMap<Color, String>(Color.class);
colorMap.put(Color.RED, "red");
colorMap.put(Color.GREEN, "green");
}
EnumMap的key是enum,value是任何其他Object对象。

参考资料:

/article/4386057.html

/article/1867408.html


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: