这个类,1.5就出了,继承AbstractMap,说白了就是个map,只是他的key是枚举:
Enummap也是线程不安全的,内部实现了迭代器,如果有线程安全问题,记得转迭代器,使用这个方法转就好enumMap.entrySet().iterator():
使用就是直接当做map就好了,为啥要使用这个类,很简单,快,进行了部分优化,所以当key为枚举的时候尽量使用这个类:
@org.junit.Test
public void test2() {
EnumMap<Season, String> enumMap = new EnumMap<>(Season.class);
HashMap<Season, String> aaa = new HashMap();
enumMap.put(Season.SPRING, "春天");
enumMap.put(Season.SUMMER, "夏天");
enumMap.put(Season.AUTUMN, "秋天");
enumMap.put(Season.WINTER, "冬天");
System.out.println(enumMap);
aaa.put(Season.SPRING, "春天");
aaa.put(Season.SUMMER, "夏天");
aaa.put(Season.AUTUMN, "秋天");
aaa.put(Season.WINTER, "冬天");
System.out.println(aaa);
}
enum Season {
SPRING, SUMMER, AUTUMN, WINTER;
}
性能比较测试:
@org.junit.Test
public void test3() {
EnumMap<Season, String> enumMap = new EnumMap<>(Season.class);
HashMap<Season, String> aaa = new HashMap();
long l = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
enumMap.put(Season.SPRING, "春天");
enumMap.put(Season.SUMMER, "夏天");
enumMap.put(Season.AUTUMN, "秋天");
enumMap.put(Season.WINTER, "冬天");
enumMap.remove(Season.SPRING);
enumMap.remove(Season.SUMMER);
enumMap.remove(Season.AUTUMN);
enumMap.remove(Season.WINTER);
}
long l2 = System.currentTimeMillis();
System.out.println(l2 - l);
long l3 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
aaa.put(Season.SPRING, "春天");
aaa.put(Season.SUMMER, "夏天");
aaa.put(Season.AUTUMN, "秋天");
aaa.put(Season.WINTER, "冬天");
aaa.remove(Season.SPRING);
aaa.remove(Season.SUMMER);
aaa.remove(Season.AUTUMN);
aaa.remove(Season.WINTER);
}
long l4 = System.currentTimeMillis();
System.out.println(l4 - l3);
}
跟enummap差不多,大部分方法跟Set差不多,只不过构建方法加了很多:
提供了很多静态的构建方法:
简单的构建方法测试:
@org.junit.Test
public void test1() {
//创建一个EnumSet集合,集合元素就是Season枚举类的全部枚举值
EnumSet es = EnumSet.allOf(Season.class);
System.out.println(es);
//创建一个EnumSet空集合,只顶其集合元素是Season类的枚举值
EnumSet es2 = EnumSet.noneOf(Season.class);
System.out.println(es2);
//以枚举值来创建EnumSet集合
EnumSet es3 = EnumSet.of(Season.SUMMER, Season.WINTER);
System.out.println(es3); //输出[SUMMER, WINTER]
//创建一个包含Season枚举值从SUMMER到WINTER的EnumSet集合
EnumSet es4 = EnumSet.range(Season.SUMMER, Season.WINTER);
System.out.println(es4);//输出[SUMMER, Fall, WINTER]
//创建一个EnumSet集合,其元素和es4集合元素类型相同, es4元素+es5元素=Sesson枚举的全部枚举值
EnumSet es5 = EnumSet.complementOf(es4);
System.out.println(es5);//输出[SPRING]
}
执行结果:
其他方法就很简单,跟set一样,只不过还是对枚举有优化;所以,如果有枚举set尽量使用这两个类