Enum(枚举)(一)
1. Enum简介
枚举是 java 1.5之后才新增的特性,主要用于常量的定义,告别之前的静态变量定义。贴一段枚举类官方介绍
/**
* This is the common base class of all Java language enumeration types.
*
* More information about enums, including descriptions of the
* implicitly declared methods synthesized by the compiler, can be
* found in section 8.9 of
* <cite>The Java™ Language Specification</cite>.
*
* <p> Note that when using an enumeration type as the type of a set
* or as the type of the keys in a map, specialized and efficient
* {@linkplain java.util.EnumSet set} and {@linkplain
* java.util.EnumMap map} implementations are available.
*
* @param <E> The enum type subclass
* @author Josh Bloch
* @author Neal Gafter
* @see Class#getEnumConstants()
* @see java.util.EnumSet
* @see java.util.EnumMap
* @since 1.5
*/
public abstract class Enum<E extends Enum<E>>
implements Comparable<E>, Serializable {}
当使用一个枚举类作为set 集合或者map中key的集合,其实就是指定义一系列相关联的常量,例如项目中用到的但是固定的值,如:状态值等
2.使用Enum
新建一个类,关键字从class 改成 enum即可。据说每一个枚举类中的常量(域)值 其实编译后都是实例化一个枚举类。举例说明:
public enum ColorEnum{
GREEN, RED, BLUE
}
//编译后 其实是这样滴
Enum<ColorEnum> green = new ColorEnum();
Enum<ColorEnum> red = new ColorEnum();
Enum<ColorEnum> blue = new ColorEnum();
//实现的枚举类是继承不了的。因为默认继承了Enum类 看下图编译的class文件
[外链图片转存失败(img-oGynizjR-1567600939505)(C:\Users\周军\AppData\Roaming\Typora\typora-user-images\1567598098366.png)]
编译后的ColorEnum
3. 常用操作
举例
public enum ColorEnum {
GREEN("绿色", 1), RED("红色", 2), BLUE("蓝色", 3);
private String color;
private Integer index;
ColorEnum(String color, Integer index){
this.color = color;
this.index = index;
}
public String getColor(){
return color;
}
public Integer getIndex(){
return index;
}
public String toString(){
return index + ":" + color;
}
public static void main(String[] args) {
//循环获取值
for(ColorEnum color : ColorEnum.values()){
System.out.println(color.toString());
}
}
}