阅读EnumSet抽象类源码

EnumSet

EnumSet是Java枚举类型的泛型容器,Java既然有了SortedSet、TreeSet、HashSet等容器,为何还要多一个EnumSet<T>呢?答案肯定是EnumSet有一定的特性,举个例子,EnumSet的速度很快。其他特性就不一一列举了,毕竟本文的内容不是介绍EnumSet的特性。

专门为枚举类设计的集合类,所有元素必须是枚举类型

EnumSet的集合元素是有序的,内部以位向量的形成存储,因此占用内存小,效率高

不允许加入null元素

源码

package java.util;

import sun.misc.SharedSecrets;

public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E>
  implements Cloneable, java.io.Serializable
{
  /**
   * 元素类型
   */
  final Class<E> elementType;

  /**
   * 通过数组存储元素
   */
  final Enum[] universe;

  private static Enum[] ZERO_LENGTH_ENUM_ARRAY = new Enum[0];

  EnumSet(Class<E>elementType, Enum[] universe) {
    this.elementType = elementType;
    this.universe  = universe;
  }

  /**
   * 创造一个空的 enum set 并制定其元素类型
   * @param elementType the class object of the element type for this enum
   *   set
   * @throws NullPointerException if <tt>elementType</tt> is null
   */
  public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
    Enum[] universe = getUniverse(elementType);
    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);
  }

  /**
   * 创建一个包含所有在指定元素类型的元素的枚举set
   *
   * @param elementType the class object of the element type for this enum
   *   set
   * @throws NullPointerException if <tt>elementType</tt> is null
   */
  public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) {
    EnumSet<E> result = noneOf(elementType);
    result.addAll();
    return result;
  }

  /**
   * Adds all of the elements from the appropriate enum type to this enum
   * set, which is empty prior to the call.
   */
  abstract void addAll();

  /**
   * 创建一个枚举设置相同的元素类型与指定枚举set
   *
   * @param s the enum set from which to initialize this enum set
   * @throws NullPointerException if <tt>s</tt> is null
   */
  public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) {
    return s.clone();
  }

  /**
   * 创建一个枚举集从指定集合初始化,最初包含相同的元素
   * @param c the collection from which to initialize this enum set
   * @throws IllegalArgumentException if <tt>c</tt> is not an
   *   <tt>EnumSet</tt> instance and contains no elements
   * @throws NullPointerException if <tt>c</tt> is null
   */
  public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) {
    if (c instanceof EnumSet) {
      return ((EnumSet<E>)c).clone();
    } else {
      if (c.isEmpty())
        throw new IllegalArgumentException("Collection is empty");
      Iterator<E> i = c.iterator();
      E first = i.next();
      EnumSet<E> result = EnumSet.of(first);
      while (i.hasNext())
        result.add(i.next());
      return result;
    }
  }

  /**
   * 创建一个枚举集合,其元素与 s 相同
   * @param s the enum set from whose complement to initialize this enum set
   * @throws NullPointerException if <tt>s</tt> is null
   */
  public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) {
    EnumSet<E> result = copyOf(s);
    result.complement();
    return result;
  }

  /**
   * 1 个元素枚举集合
   *
   * @param e the element that this set is to contain initially
   * @throws NullPointerException if <tt>e</tt> is null
   * @return an enum set initially containing the specified element
   */
  public static <E extends Enum<E>> EnumSet<E> of(E e) {
    EnumSet<E> result = noneOf(e.getDeclaringClass());
    result.add(e);
    return result;
  }

  /**
   * 2 个元素枚举集合
   *
   * @param e1 an element that this set is to contain initially
   * @param e2 another element that this set is to contain initially
   * @throws NullPointerException if any parameters are null
   * @return an enum set initially containing the specified elements
   */
  public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) {
    EnumSet<E> result = noneOf(e1.getDeclaringClass());
    result.add(e1);
    result.add(e2);
    return result;
  }

  /**
   * 3 个元素枚举集合
   *
   * @param e1 an element that this set is to contain initially
   * @param e2 another element that this set is to contain initially
   * @param e3 another element that this set is to contain initially
   * @throws NullPointerException if any parameters are null
   * @return an enum set initially containing the specified elements
   */
  public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) {
    EnumSet<E> result = noneOf(e1.getDeclaringClass());
    result.add(e1);
    result.add(e2);
    result.add(e3);
    return result;
  }

  /**
   * 4 个元素枚举集合
   * @param e1 an element that this set is to contain initially
   * @param e2 another element that this set is to contain initially
   * @param e3 another element that this set is to contain initially
   * @param e4 another element that this set is to contain initially
   * @throws NullPointerException if any parameters are null
   * @return an enum set initially containing the specified elements
   */
  public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4) {
    EnumSet<E> result = noneOf(e1.getDeclaringClass());
    result.add(e1);
    result.add(e2);
    result.add(e3);
    result.add(e4);
    return result;
  }

  /**
   * 5 个元素枚举集合
   *
   * @param e1 an element that this set is to contain initially
   * @param e2 another element that this set is to contain initially
   * @param e3 another element that this set is to contain initially
   * @param e4 another element that this set is to contain initially
   * @param e5 another element that this set is to contain initially
   * @throws NullPointerException if any parameters are null
   * @return an enum set initially containing the specified elements
   */
  public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4,
                          E e5)
  {
    EnumSet<E> result = noneOf(e1.getDeclaringClass());
    result.add(e1);
    result.add(e2);
    result.add(e3);
    result.add(e4);
    result.add(e5);
    return result;
  }

  /**
   * n 个元素枚举集合
   *
   * @param first an element that the set is to contain initially
   * @param rest the remaining elements the set is to contain initially
   * @throws NullPointerException if any of the specified elements are null,
   *   or if <tt>rest</tt> is null
   * @return an enum set initially containing the specified elements
   */
  @SafeVarargs
  public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) {
    EnumSet<E> result = noneOf(first.getDeclaringClass());
    result.add(first);
    for (E e : rest)
      result.add(e);
    return result;
  }

  /**
   * 区间内元素的 枚举集合
   *
   * @param from the first element in the range
   * @param to the last element in the range
   * @throws NullPointerException if {@code from} or {@code to} are null
   * @throws IllegalArgumentException if {@code from.compareTo(to) > 0}
   * @return an enum set initially containing all of the elements in the
   *     range defined by the two specified endpoints
   */
  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;
  }

  /**
   * Adds the specified range to this enum set, which is empty prior
   * to the call.
   */
  abstract void addRange(E from, E to);

  /**
   * Returns a copy of this set.
   *
   * @return a copy of this set
   */
  public EnumSet<E> clone() {
    try {
      return (EnumSet<E>) super.clone();
    } catch(CloneNotSupportedException e) {
      throw new AssertionError(e);
    }
  }

  /**
   * Complements the contents of this enum set.
   */
  abstract void complement();

  /**
   * Throws an exception if e is not of the correct type for this enum set.
   */
  final void typeCheck(E e) {
    Class eClass = e.getClass();
    if (eClass != elementType && eClass.getSuperclass() != elementType)
      throw new ClassCastException(eClass + " != " + elementType);
  }

  /**
   * Returns all of the values comprising E.
   * The result is uncloned, cached, and shared by all callers.
   */
  private static <E extends Enum<E>> E[] getUniverse(Class<E> elementType) {
    return SharedSecrets.getJavaLangAccess()
                    .getEnumConstantsShared(elementType);
  }

  /**
   * This class is used to serialize all EnumSet instances, regardless of
   * implementation type. It captures their "logical contents" and they
   * are reconstructed using public static factories. This is necessary
   * to ensure that the existence of a particular implementation type is
   * an implementation detail.
   *
   * @serial include
   */
  private static class SerializationProxy <E extends Enum<E>>
    implements java.io.Serializable
  {
    /**
     * The element type of this enum set.
     *
     * @serial
     */
    private final Class<E> elementType;

    /**
     * The elements contained in this enum set.
     *
     * @serial
     */
    private final Enum[] elements;

    SerializationProxy(EnumSet<E> set) {
      elementType = set.elementType;
      elements = set.toArray(ZERO_LENGTH_ENUM_ARRAY);
    }

    private Object readResolve() {
      EnumSet<E> result = EnumSet.noneOf(elementType);
      for (Enum e : elements)
        result.add((E)e);
      return result;
    }

    private static final long serialVersionUID = 362491234563181265L;
  }

  Object writeReplace() {
    return new SerializationProxy<>(this);
  }

  // readObject method for the serialization proxy pattern
  // See Effective Java, Second Ed., Item 78.
  private void readObject(java.io.ObjectInputStream stream)
    throws java.io.InvalidObjectException {
    throw new java.io.InvalidObjectException("Proxy required");
  }
}

总结

以上就是本文关于阅读EnumSet抽象类源码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

(0)

相关推荐

  • java.lang.Void类源码解析

    在一次源码查看ThreadGroup的时候,看到一段代码,为以下: /* * @throws NullPointerException if the parent argument is {@code null} * @throws SecurityException if the current thread cannot create a * thread in the specified thread group. */ private static Void checkParentAcc

  • 浅谈Java多线程处理中Future的妙用(附源码)

    java 中Future是一个未来对象,里面保存这线程处理结果,它像一个提货凭证,拿着它你可以随时去提取结果.在两种情况下,离开Future几乎很难办.一种情况是拆分订单,比如你的应用收到一个批量订单,此时如果要求最快的处理订单,那么需要并发处理,并发的结果如果收集,这个问题如果自己去编程将非常繁琐,此时可以使用CompletionService解决这个问题.CompletionService将Future收集到一个队列里,可以按结果处理完成的先后顺序进队.另外一种情况是,如果你需要并发去查询一

  • Java实现打飞机小游戏(附完整源码)

    写在前面 技术源于分享,所以今天抽空把自己之前用java做过的小游戏整理贴出来给大家参考学习.java确实不适合写桌面应用,这里只是通过这个游戏让大家理解oop面向对象编程的过程,纯属娱乐.代码写的很简单,也很容易理解,并且注释写的很清楚了,还有问题,自己私下去补课学习. 效果如下 完整代码 敌飞机 import java.util.Random; 敌飞机: 是飞行物,也是敌人 public class Airplane extends FlyingObject implements Enemy

  • Java+MySQL实现学生信息管理系统源码

    基于Java swing+MySQL实现学生信息管理系统:主要实现JDBC对学生信息进行增删改查,应付一般课设足矣,分享给大家.(由于篇幅原因,代码未全部列出,如有需要留下邮箱) 鉴于太多同学要源码,实在发不过来,上传到github上 https://github.com/ZhuangM/student.git 1. 开发环境:jdk7+MySQL5+win7 代码结构:model-dao-view 2. 数据库设计--建库建表语句: CREATE DATABASE student; DROP

  • java(swing)+ mysql实现学生信息管理系统源码

    本文实例为大家分享了java实现学生信息管理系统源码,供大家参考,具体内容如下 import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import

  • Java版坦克大战游戏源码示例

    整理文档,搜刮出一个Java版坦克大战游戏的代码,稍微整理精简一下做下分享. package tankwar; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.FileInputStream; imp

  • Java源码解析之object类

    在源码的阅读过程中,可以了解别人实现某个功能的涉及思路,看看他们是怎么想,怎么做的.接下来,我们看看这篇Java源码解析之object的详细内容. Java基类Object java.lang.Object,Java所有类的父类,在你编写一个类的时候,若无指定父类(没有显式extends一个父类)编译器(一般编译器完成该步骤)会默认的添加Object为该类的父类(可以将该类反编译看其字节码,不过貌似Java7自带的反编译javap现在看不到了). 再说的详细点:假如类A,没有显式继承其他类,编译

  • Java GUI编程之贪吃蛇游戏简单实现方法【附demo源码下载】

    本文实例讲述了Java GUI编程之贪吃蛇游戏简单实现方法.分享给大家供大家参考,具体如下: 例子简单,界面简陋 请见谅 项目结构如下 Constant.jvava 代码如下: package snake; /** * * @author hjn * */ public class Constant { /** * 蛇方移动方向:左边 */ public static final int LEFT = 0; /** * 蛇方移动方向:右边 */ public static final int R

  • 阅读EnumSet抽象类源码

    EnumSet EnumSet是Java枚举类型的泛型容器,Java既然有了SortedSet.TreeSet.HashSet等容器,为何还要多一个EnumSet<T>呢?答案肯定是EnumSet有一定的特性,举个例子,EnumSet的速度很快.其他特性就不一一列举了,毕竟本文的内容不是介绍EnumSet的特性. 专门为枚举类设计的集合类,所有元素必须是枚举类型 EnumSet的集合元素是有序的,内部以位向量的形成存储,因此占用内存小,效率高 不允许加入null元素 源码 package ja

  • Java杂谈之合格程序员一定要会阅读别人的源码

    目录 找 预览运行效果 下载(用idea拉取代码) 看 运行 安装数据库 安装前端依赖 后端maven更换等 分析架构 Run一下 启动前端 前后端分离项目的套路 如何找到一个好的开源项目 gitee github 学会阅读别人的源码 找预览运行效果下载(用idea拉取代码)看运行安装数据库安装前端依赖后端maven更换等分析架构Run一下启动前端 前后端分离项目的套路如何找到一个好的开源项目giteegithub 找 预览运行效果 下载(用idea拉取代码) 然后分别下载前端工程和后端工程 g

  • jdk源码阅读Collection详解

    见过一句夸张的话,叫做"没有阅读过jdk源码的人不算学过java".从今天起开始精读源码.而适合精读的源码无非就是java.io,.util和.lang包下的类. 面试题中对于集合的考察还是比较多的,所以我就先从集合的源码开始看起. (一)首先是Collection接口. Collection是所有collection类的根接口;Collection继承了Iterable,即所有的Collection中的类都能使用foreach方法. /** * Collection是所有collec

  • Intellij IDEA 阅读源码的 4 个绝技(必看)

    前段时间分享了<阅读跟踪 Java 源码的几个小技巧>是基于 Eclipse 版本的,看大家的留言都是想要 IDEA 版本的源码阅读技巧. 所以,为了满足众多 IDEA 粉丝的要求,栈长我特意做一期 IDEA 版的. 1.定位到方法实现类 public static Object getBean(String name) { return applicationContext.getBean(name); } 如以上代码,IDEA 如何跳转到 getBean 方法的实现类? 在 IDEA 中,

  • springboot-2.3.x最新版源码阅读环境搭建(基于gradle构建)

    一.前言 跟很多小伙伴聊天,发现一个严重的问题,很多小伙伴横向发展的貌似很不错,很多技术都能说出一二,但是如果在某个技术上深挖一下就不行了,问啥啥不会.就拿springboot来说,很多同学止步于springboot的应用,再往深处就一问三不知了,那么如何破局呢?smart哥认为最好的办法就是直捣黄龙,要把一个技术理解透了,听别人讲一万遍原理,不如自己撕一遍源码. 要阅读源码那就首先得先搭建源码阅读环境,那么本篇文章就来介绍下Spring Boot的源码环境搭建. 鉴于spring团队已经全面抛

  • Android图片加载利器之Picasso源码解析

    看到了这里,相信大家对Picasso的使用已经比较熟悉了,本篇博客中将从基本的用法着手,逐步的深入了解其设计原理. Picasso的代码量在众多的开源框架中算得上非常少的一个了,一共只有35个class文件,但是麻雀虽小,五脏俱全.好了下面跟随我的脚步,出发了. 基本用法 Picasso.with(this).load(imageUrl).into(imageView); with(this)方法 public static Picasso with(Context context) { if

  • Python中getpass模块无回显输入源码解析

    本文主要讨论了python中getpass模块的相关内容,具体如下. getpass模块 昨天跟学弟吹牛b安利Python标准库官方文档的时候偶然发现了这个模块.仔细一看内容挺少的,只有两个主要api,就花了点时间阅读了一下源码,感觉挺实用的,在这安利给大家. getpass.getpass(prompt='Password: ', stream=None) 调用该函数可以在命令行窗口里面无回显输入密码.参数prompt代表提示字符串,默认是'Password: '.在Unix系统中,strea

  • Django restframework 源码分析之认证详解

    前言 最近学习了 django 的一个 restframework 框架,对于里面的执行流程产生了兴趣,经过昨天一晚上初步搞清楚了执行流程(部分方法还不太清楚),于是想详细的总结一下当来一个请求时,在该框架里面是如何执行的? 启动项目时 昨天在调试django时,发现在 APIView 中打的断点没有断下来,而是打在 View 中的断点断下来了,调试了很多次,最后发现,在 django 项目启动时,会首先加载 urls 中的文件,执行 views 中类的 as_view方法,其实是继承自 API

  • 详解webpack-dev-middleware 源码解读

    前言 Webpack 的使用目前已经是前端开发工程师必备技能之一.若是想在本地环境启动一个开发服务,大家只需在 Webpack 的配置中,增加 devServer的配置来启动.devServer 配置的本质是 webpack-dev-server 这个包提供的功能,而 webpack-dev-middleware 则是这个包的底层依赖. 截至本文发表前,webpack-dev-middleware 的最新版本为 webpack-dev-middleware@3.7.2,本文的源码来自于此版本.本

  • 解析ConcurrentHashMap: put方法源码分析

    上一章:预热(内部一些小方法分析) put()方法是并发HashMap源码分析的重点方法,这里涉及到并发扩容,桶位寻址等等- JDK1.8 ConcurrentHashMap结构图: 1.put方法源码解析 // 向并发Map中put一个数据 public V put(K key, V value) { return putVal(key, value, false); } // 向并发Map中put一个数据 // Key: 数据的键 // value:数据的值 // onlyIfAbsent:

随机推荐