1. 使用场景
当key为枚举的时候使用
2. 代码
package com.hz.collections.enummap;
import java.util.EnumMap;
/**
* @fileName: EnumMapTest
* @version:
* @description:
* @author: pp_lan
* @date: 2022/3/29
*/
public class EnumMapTest {
public static void main(String[] args) {
EnumMap<StateEnum, String> map = new EnumMap<>(StateEnum.class);
map.put(StateEnum.WAKE_UP, "wakeUp resolve");
map.put(StateEnum.BREAKFAST, "breakfast resolve");
map.put(StateEnum.WORK, "work resolve");
String resolveMethod = map.get(StateEnum.BREAKFAST);
System.out.println(resolveMethod);
}
}
3. 执行结果
breakfast resolve
4. 源码分析
4.1 构造方法中传入一个Class在get的时候进行校验
/**
* Creates an empty enum map with the specified key type.
*
* @param keyType the class object of the key type for this enum map
* @throws NullPointerException if <tt>keyType</tt> is null
*/
public EnumMap(Class<K> keyType) {
this.keyType = keyType;
keyUniverse = getKeyUniverse(keyType);
vals = new Object[keyUniverse.length];
}
4.2 get
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key == k)},
* then this method returns {@code v}; otherwise it returns
* {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*/
public V get(Object key) {
return (isValidKey(key) ?
unmaskNull(vals[((Enum<?>)key).ordinal()]) : null);
}
4.3 isValidKey校验key类型是否和定义的一致
/**
* Returns true if key is of the proper type to be a key in this
* enum map.
*/
private boolean isValidKey(Object key) {
if (key == null)
return false;
// Cheaper than instanceof Enum followed by getDeclaringClass
Class<?> keyClass = key.getClass();
return keyClass == keyType || keyClass.getSuperclass() == keyType;
}
4.4 空值判断
private V unmaskNull(Object value) {
return (V)(value == NULL ? null : value);
}