Skip to content

Commit ce4b451

Browse files
Create EnumMapDemo.java
1 parent bd0452c commit ce4b451

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package learnCollections;
2+
3+
import java.util.EnumMap;
4+
import java.util.Map;
5+
6+
/*
7+
- if all the keys in Map are values of a single enum, it's recommended to use EnumMap. It has advantage of knowing all possible keys in advance
8+
- it is more efficient compared to other implementations, as it internally uses a simple array
9+
*/
10+
11+
public class EnumMapDemo {
12+
public static void main(String[] args) {
13+
// array of size same as enum
14+
// [_, "Gym", _, _, _, _, _]
15+
// no hashing
16+
// ordinal / index is used
17+
// faster than HashMap
18+
// memory efficient
19+
// ordered by enum declaration order
20+
Map<Day, String> map = new EnumMap<>(Day.class);
21+
map.put(Day.TUESDAY, "Gym");
22+
map.put(Day.MONDAY, "Walk");
23+
System.out.println(map); // {MONDAY=Walk, TUESDAY=Gym}
24+
25+
System.out.println(Day.TUESDAY.ordinal()); // 1 --> index
26+
}
27+
}
28+
29+
enum Day {
30+
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
31+
}

0 commit comments

Comments
 (0)