EnumMap的使用
基础使用
package com.ojxchen; import java.util.EnumMap; public class EnumMapTest { enum Color { RED, GREEN, BLUE } public static void main(String[] args) { EnumMap<Color, Object> enumMap = new EnumMap<>(Color.class); enumMap.put(Color.RED, "red"); enumMap.put(Color.GREEN, "green"); enumMap.put(Color.BLUE, "blue"); enumMap.forEach((k, v) -> System.out.println(k + ":" + v)); } }
高级使用
package com.ojxchen; import java.util.EnumMap; interface Command { void execute(); } class StartCommand implements Command{ @Override public void execute() { System.out.println("Start command executed"); } } class StopCommand implements Command{ @Override public void execute() { System.out.println("Stop command executed"); } } enum CommandType { START, STOP } public class CommandExample { private static final EnumMap<CommandType, Command> commandMap = new EnumMap<>(CommandType.class); static { commandMap.put(CommandType.START, new StartCommand()); commandMap.put(CommandType.STOP, new StopCommand()); } public static void main(String[] args) { Command command = commandMap.get(CommandType.START); command.execute(); command = commandMap.get(CommandType.STOP); command.execute(); } }

浙公网安备 33010602011771号