首页 > 代码库 > 用枚举enum替代int常量

用枚举enum替代int常量

枚举的好处:

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=http://www.mamicode.com/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常量