向 enum里面添加类型
public enum OzWitch {
WEST("Miss Gulch, aka Dorothy's Auntie Em", "Munchkins"),
NORTH("Glenda the Good Witch", "Gillikins"),
EAST("Evloc, aka the Wicked Witch of the East", "Winkies"),
SOUTH("Locasta, aka the Good Witch of the South", "Quadlings");
private final String description;
private final String inhabitants;
private OzWitch(String description, String inhabitants) {
this.description = description;
this.inhabitants = inhabitants;
}
public String getDescription() {
return description;
}
public static void main(String[] args) {
for (OzWitch witch : OzWitch.values()) {
System.out.println(witch + ": " + witch.getDescription() + ", " + witch.inhabitants);
}
}
}
覆盖enum的toString的方法
public enum SpaceShip {
SCOUT, CARGO, TRANSPORT, BATTLE;
public String toString() {
String id = name();
String lower = id.substring(1).toLowerCase();
return id.charAt(0) + lower;
}
public static void main(String[] args) {
for (SpaceShip s : SpaceShip.values()) {
System.out.println(s);
}
}
}
Switch中使用enum
enum Signal {
RED, GREEN, YELLOW
}
public class TrafficLight {
Signal color = Signal.RED;
public void change() {
switch (color) {
case RED -> color = Signal.GREEN;
case GREEN -> color = Signal.YELLOW;
case YELLOW -> color = Signal.RED;
}
}
public String toString() {
return "The traffic light is " + color;
}
public static void main(String[] args) {
TrafficLight light = new TrafficLight();
for (int i = 0; i < 7; i++) {
System.out.println(light);
light.change();
}
}
}
BigEnumSet 使用方式
import java.util.EnumSet;
public class BigEnumSet {
// Class implementation goes here
enum Big {
A0, A1, A2, A3, A4, A5, A6, A7, A8, A9,
A10, A11, A12, A13, A14, A15, A16, A17, A18, A19,
A20, A21, A22, A23, A24, A25, A26, A27, A28, A29,
A30, A31, A32, A33, A34, A35, A36, A37, A38, A39,
A40, A41, A42, A43, A44, A45, A46, A47, A48, A49,
A50, A51, A52, A53, A54, A55, A56, A57, A58, A59,
A60, A61, A62, A63, A64, A65, A66, A67, A68, A69,
A70, A71, A72, A73, A74, A75
}
public static void main(String[] args) {
EnumSet<Big> bigEnumSet = EnumSet.allOf(Big.class);
System.out.println("BigEnumSet contains: " + bigEnumSet);
}
}