Java 使用枚举定义常量

前言

JDK1.5之后出现了枚举类型,最近在公司的项目中一直出现了枚举,发现枚举真香。对于项目比较庞大的,使用枚举不仅可以增加代码的可读性,也就是大佬们说的“优雅”,还有利于后期代码的维护。枚举比较常用的场景就是用于常量的定义,但是相比于使用“static final”,枚举类型会增加内存的消耗,这个就是枚举的缺点,但是对于目前的硬件来说,这点还是可以忽略的。

使用枚举定义常量

package com.chen.mykinthtest.test;

public enum Color {

    RED("红色", 1),
    GREEN("绿色", 2),
    BLUE("蓝色", 3);

    private String code;
    private int index;

    private Color(String code, int index) {
        this.code = code;
        this.index = index;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }
}
package com.chen.mykinthtest.test;

public class ColorTest {

    public static void main(String[] args) {
        String code = Color.RED.getCode();
        for(Color c:Color.values()){
            System.out.println("code"+c.getCode()+"  index:"+c.getIndex());
        }

    }
}
发布了133 篇原创文章 · 获赞 75 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_42109746/article/details/104244379