2015-04-20 15:36:01 -07:00
|
|
|
//: enumerated/EnumMaps.java
|
|
|
|
// Basics of EnumMaps.
|
|
|
|
package enumerated;
|
|
|
|
import java.util.*;
|
|
|
|
import static enumerated.AlarmPoints.*;
|
|
|
|
import static net.mindview.util.Print.*;
|
|
|
|
|
|
|
|
interface Command { void action(); }
|
|
|
|
|
|
|
|
public class EnumMaps {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
EnumMap<AlarmPoints,Command> em =
|
2015-05-05 11:20:13 -07:00
|
|
|
new EnumMap<>(AlarmPoints.class);
|
2015-05-05 14:05:39 -07:00
|
|
|
em.put(KITCHEN, (Command) () -> {
|
|
|
|
print("Kitchen fire!");
|
2015-04-20 15:36:01 -07:00
|
|
|
});
|
2015-05-05 14:05:39 -07:00
|
|
|
em.put(BATHROOM, (Command) () -> {
|
|
|
|
print("Bathroom alert!");
|
2015-04-20 15:36:01 -07:00
|
|
|
});
|
|
|
|
for(Map.Entry<AlarmPoints,Command> e : em.entrySet()) {
|
|
|
|
printnb(e.getKey() + ": ");
|
|
|
|
e.getValue().action();
|
|
|
|
}
|
|
|
|
try { // If there's no value for a particular key:
|
|
|
|
em.get(UTILITY).action();
|
|
|
|
} catch(Exception e) {
|
2015-04-29 12:53:35 -07:00
|
|
|
print("Expected: " + e);
|
2015-04-20 15:36:01 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} /* Output:
|
|
|
|
BATHROOM: Bathroom alert!
|
|
|
|
KITCHEN: Kitchen fire!
|
2015-04-29 12:53:35 -07:00
|
|
|
Expected: java.lang.NullPointerException
|
2015-05-05 11:20:13 -07:00
|
|
|
*///:~
|