EnumMap(A Guide to EnumMap)

public enum DayOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Creation

EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");

EnumMap Copy Constructor

EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");

EnumMap<DayOfWeek, String> activityMapCopy = new EnumMap<>(activityMap);

System.out.println(activityMapCopy.size()); // 2
System.out.println(activityMapCopy.get(DayOfWeek.MONDAY)); // Soccer

Map Copy Constructor

Map<DayOfWeek, String> ordinaryMap = new HashMap();
ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");

EnumMap enumMap = new EnumMap(ordinaryMap);

System.out.println(activityMapCopy.size()); // 2
System.out.println(activityMapCopy.get(DayOfWeek.MONDAY)); // Soccer

基础方法

ordinaryMap.put(DayOfWeek.MONDAY, "Soccer");

activityMapCopy.get(DayOfWeek.MONDAY)

ordinaryMap.containsKey(DayOfWeek.MONDAY)

ordinaryMap.size()

null as Value

EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");

System.out.println(activityMap.containsKey(DayOfWeek.SATURDAY)); // false
System.out.println(activityMap.containsValue(null)); // false

activityMap.put(DayOfWeek.SATURDAY, null);
System.out.println(activityMap.containsKey(DayOfWeek.SATURDAY)); // true
System.out.println(activityMap.containsValue(null)); // true

Removing Elements

EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");

System.out.println(activityMap.remove(DayOfWeek.MONDAY)); // Soccer
System.out.println(activityMap.containsKey(DayOfWeek.MONDAY)); // false
activityMap.put(DayOfWeek.MONDAY, "Soccer");
System.out.println(activityMap.remove(DayOfWeek.MONDAY, "Hiking")); // false
System.out.println(activityMap.remove(DayOfWeek.MONDAY, "Soccer")); // true

values、keySet、entrySet

EnumMap<DayOfWeek, String> activityMap = new EnumMap<>(DayOfWeek.class);
activityMap.put(DayOfWeek.MONDAY, "Soccer");
activityMap.put(DayOfWeek.TUESDAY, "Basketball");

Collection<String> values = activityMap.values();

Set<DayOfWeek> dayOfWeeks = activityMap.keySet();

Set<Map.Entry<DayOfWeek, String>> entries = activityMap.entrySet();

你可能感兴趣的:(Baeldung,学习笔记,集合,java,前端,服务器)