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



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值