Enum(枚举)(一)

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&trade; 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());
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值