JAVA中enum的常见用法

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对象。


参考资料:

http://android.blog.51cto.com/268543/563950

http://blog.csdn.net/mqboss/article/details/5647851



原文地址:https://www.cnblogs.com/dyllove98/p/3190216.html