EnumSet源码解析
2015-11-14 23:51
351 查看
EnumSet源码解析
现在我们来说说EnumSet,很多人以为EnumSet没有用处,那为什么JDK要特意加上这么一个类呢?我们来看看这样一个使用场景:
Enum Property{A,B,C,D,E,F}
public void getEntity(Set propertys){}
根据不同的属性获取不同的对象,这些属性可以任意组合。这好像是位域的使用范围。
对的,EnumSet既有位域的简洁和性能优势,又具有枚举的直观易用的优点。
上述例子,我们可以使用
getEntity(EnumSet.of(Property.A,Property.B))
EnumSet是个抽象类,我们只能通过它提供的静态方法来返回Enumset的实现类的实例,它提供了很多有用的方法
EnumSet.allOf(Property.class) // all elements EnumSet.range(Property.A,Property.C) //A,B,C
这是它的易用性,那么来看看它的性能优势是怎么体现的呢?
我们看一下源码:
public static <E extends Enum<E>> EnumSet<E> range(E from, E to) { if (from.compareTo(to) > 0) throw new IllegalArgumentException(from + " > " + to); EnumSet<E> result = noneOf(from.getDeclaringClass()); result.addRange(from, to); return result; } abstract void addRange(E from, E to); public static <E extends Enum<E>> EnumSet<E> of(E e) { EnumSet<E> result = noneOf(e.getDeclaringClass()); result.add(e); return result; } abstract void addAll();
我们调用EnumSet的静态方法创建实例时,都会调用noneOf返回一个EnumSet的实例,不同的实例会实现不同的抽象方法。那么我们来看看这个noneOf方法
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) { Enum<?>[] universe = getUniverse(elementType); //Returns all of the values comprising E if (universe == null) throw new ClassCastException(elementType + " not an enum"); if (universe.length <= 64) return new RegularEnumSet<>(elementType, universe); else return new JumboEnumSet<>(elementType, universe); }
可以看出,如果Enum的个数小于等于64,使用的就是RegularEnumSet这个实现,否则JumboEnumSet。
相关文章推荐
- 从源码安装Mysql/Percona 5.5
- Ubuntu 安装 JDK 问题
- 浅析Ruby的源代码布局及其编程风格
- asp.net 抓取网页源码三种实现方法
- JS小游戏之仙剑翻牌源码详解
- JS小游戏之宇宙战机源码详解
- jQuery源码分析之jQuery中的循环技巧详解
- 本人自用的global.js库源码分享
- java中原码、反码与补码的问题分析
- jdk与jre的区别 很形象,很清晰,通俗易懂
- jdk中String类设计成final的原由
- win7下安装 JDK 基本流程
- jdk环境变量配置
- win2003 jsp运行环境架设心得(jdk+tomcat)
- windows linux jdk安装配置方法
- PHP网页游戏学习之Xnova(ogame)源码解读(六)
- C#获取网页HTML源码实例
- PHP网页游戏学习之Xnova(ogame)源码解读(八)
- PHP网页游戏学习之Xnova(ogame)源码解读(四)
- 简单记录Cent OS服务器配置JDK+Tomcat+MySQL