EnumSet源码解析

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值