EnumMap使用

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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值