您的位置:首页 > 编程语言 > Java开发

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jdk 源码