Java枚举总结

Java枚举总结

枚举类型比较简单,下面两个文章讲的比较清楚:

  • Java 枚举(enum) 详解7种常见的用法
  • 深入理解Java枚举类型(enum)

附上实验代码:


package com.minghui.test;

import java.util.EnumMap;
import java.util.EnumSet;

public enum Color implements Pritable {
    RED("红"), YELLOW("黄"), BLUE("蓝");

    public String mChineseName;

    private Color(String chineseName) {
        mChineseName = chineseName;
    }

    @Override
    public String toString() {
        return mChineseName;
    }

    @Override
    public void print() {
        System.out.println("index : " + ordinal() + " name :" + super.toString());
    }

    public static void main(String[] args) {
        System.out.println("RED :" + RED + " YELLOW:" + YELLOW + " BLUE:" + BLUE);
        RED.print();
        YELLOW.print();
        BLUE.print();
        printColor(RED);
        printColor(YELLOW);
        printColor(BLUE);
        EnumMap colorMap = new EnumMap<>(Color.class);
        colorMap.put(RED, "FF0000");
        colorMap.put(YELLOW, "0000FF");
        colorMap.put(BLUE, "00FF00");

        for (Color color : colorMap.keySet()) {
            System.out.println("RGB Value of  :" + color + " is " + colorMap.get(color));
        }

        EnumSet colorAllSet = EnumSet.allOf(Color.class);
        System.out.println("colorAllSet set  :" + colorAllSet);
        EnumSet subColorSet = EnumSet.of(YELLOW, BLUE);
        System.out.println("colorAllSet set  :" + colorAllSet);
        EnumSet emptyColorSet = EnumSet.noneOf(Color.class);
        System.out.println("emptyColorSet set  :" + emptyColorSet);
        EnumSet oppColorSet = EnumSet.complementOf(subColorSet);
        System.out.println("oppColorSet set  :" + oppColorSet);
    }

    public static void printColor(Color color) {
        String description;
        switch (color) {
            case BLUE:
                description = "BLUE";
                break;
            case RED:
                description = "RED";
                break;
            default:
                description = "YELLOW";
        }

        System.out.println("Color is: " + description + " Chinese name is "
                + color.mChineseName);
    }
}

public interface Pritable {
    void print();
}

你可能感兴趣的:(Java枚举总结)