首页 技术 正文
技术 2022年11月15日
0 收藏 510 点赞 4,453 浏览 1485 个字

  在平常的项目中,enumMap是比较少用到的一种map,一般都不会使用到这种容器,那么我将从如下几个方面来阐述我对enumMap的理解

1、使用场景

  在key是比较固定的情况下,使用enumMap是最适合不过的,如我的水果摊中,就有如下几种水果:Fruit.APPLE,Fruit.BANANA,Fruit.PEAR,Fruit.GRAPE,那么这几种水果的价格是

EnumMap enumMap=new EnumMap(Fruit.class);
enumMap.put(Fruit.APPLE,"9/kg");
enumMap.put(Fruit.BANANA,"5/kg");
enumMap.put(Fruit.PEAR,"6/kg");
enumMap.put(Fruit.GRAPE,"20/kg");

当有人问我苹果的价格的时候,我会告诉他,苹果是这个价格

enumMap.get(enumMap.APPLE);

2、jdk说明

A specialized {@link Map} implementation for use with enum type keys.  All
* of the keys in an enum map must come from a single enum type that is
* specified, explicitly or implicitly, when the map is created. Enum maps
* are represented internally as arrays. This representation is extremely
* compact and efficient.
*
* <p>Enum maps are maintained in the <i>natural order</i> of their keys
* (the order in which the enum constants are declared). This is reflected
* in the iterators returned by the collections views ({@link #keySet()},
* {@link #entrySet()}, and {@link #values()}).
也就是说,enumMap是一个支持使用enum类型作为key的map,内部是使用数组来存储的,所以是非常高效和整洁的。

3、源码探索

put方法:

 public V put(K key, V value) {
typeCheck(key); int index = key.ordinal();
Object oldValue = vals[index];
vals[index] = maskNull(value);
if (oldValue == null)
size++;
return unmaskNull(oldValue);
}
private V unmaskNull(Object value) {
return (V)(value == NULL ? null : value);
}

从这个看出,如果key是null,则会抛出NullPointerException,如果这个key对应的值如果有旧值,就会使用旧值来代替新值。

get方法:

public V get(Object key) {
return (isValidKey(key) ?
unmaskNull(vals[((Enum<?>)key).ordinal()]) : null);
}
private V unmaskNull(Object value) {
return (V)(value == NULL ? null : value);
}

在get方法中,如果key和你的keyType不一致的时候,将会返回null


    					
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,020
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,513
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,359
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,142
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,772
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,850