zoukankan      html  css  js  c++  java
  • 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


    
    
  • 相关阅读:
    shell 测试命令
    shell 键盘录入和运算
    shell 的变量
    shell 脚本 helloworld
    让windows系统的DOS窗口也可以显示utf8字符集
    wxpython发布还自己图标的程序
    弥补wxpython无背景图片缺陷
    wxPython实现在浏览器中打开链接
    使用py2exe发布windows平台Python
    python os模块实用函数
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3190216.html
Copyright © 2011-2022 走看看