8.1 enum类型

    xiaoxiao2025-02-17  22

    enum与Enumeration区别: enum用来声明类,Enumeration是容器。Enumeration见第8节。

    用法一:

    把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。

    public enum Color { RED, GREEN, BLANK, YELLOW }

    怎样把枚举类变为数组?

    enum Light { RED(1), GREEN(3), YELLOW(2); ......... } // 将枚举里的常量变到数组中 Light[] allLight = Light.values(); for (Light aLight : allLight) { System.out.println("当前灯name:" + aLight.name()); }

    用法二:switch

    JDK1.6之前的switch语句只支持int,char,enum类型,使用枚举,能让我们的代码可读性更强。

    enum Signal { GREEN, YELLOW, RED } public class TrafficLight { // enum类里的对象也是该类类型的 Signal color = Signal.RED; public void change() { switch (color) { case RED: color = Signal.GREEN; break; case YELLOW: color = Signal.RED; break; case GREEN: color = Signal.YELLOW; break; } } }

    用法三:向枚举中添加新方法

    public enum Color { RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4); // 成员变量 private String name; private int index; // 构造方法 private Color(String name, int index) { this.name = name; this.index = index; } // 普通方法 public static String getName(int index) { for (Color c : Color.values()) { if (c.getIndex() == index) { return c.name; } } return null; } // get set 方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }

    用法四:实现接口

    interface Behaviour { void print(); String getInfo(); } enum Color implements Behaviour { RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4); private String name; private int index; private Color(String name, int index) { this.name = name; this.index = index; } // 接口方法 @Override public String getInfo() { return name; } public void print() { System.out.println(index + ":" + name); } } 调用时: Color.GREEN.print();
    转载请注明原文地址: https://ju.6miu.com/read-1296524.html
    最新回复(0)