首页 > 编程语言 > 详细

用枚举enum替代int常量

时间:2016-12-06 20:03:10      阅读:193      评论:0      收藏:0      [点我收藏+]

枚举的好处:

1. 类型安全性

2.使用方便性

 

public class EnumDemo {     
    enum Color{     
        RED(3),BLUE(5),BLACK(8),YELLOW(13),GREEN(28);          
        private int colorValue;     
        private Color(int rv){     
         this.colorValue=rv;       
        }   
        private int getColorValue(){
            return colorValue;
        }   
        
        private int value(){
            return ordinal()+1;
        }
}          
    public static void main(String[] args) { 
        for(Color s : Color.values()) {     
            //enum的values()返回一个数组,这里就是Seasons[]     
            System.out.println(s.value()+":"+s.name()+"="+s.getColorValue());     
        }     
    }     
}   

output:

1:RED=3
2:BLUE=5
3:BLACK=8
4:YELLOW=13
5:GREEN=28

其中,

    /**
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     *
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant
     */
    public final int ordinal() {
        return ordinal;
    }

 

用枚举enum替代int常量

原文:http://www.cnblogs.com/davidwang456/p/6138717.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!