码迷,mamicode.com
首页 > 编程语言 > 详细

用枚举enum替代int常量

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

标签:signed   ant   类型   mmap   etc   ase   link   data   tco   

枚举的好处:

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常量

标签:signed   ant   类型   mmap   etc   ase   link   data   tco   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!