Java 简明教程

Java EnumSet Class

Introduction

Java EnumSet 类是专门用于 enum 类型的 Set 实现。以下是对 EnumSet 的重要说明−

The Java EnumSet class is a specialized Set implementation for use with enum types. Following are the important points about EnumSet −

  1. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.

  2. Enum sets are represented internally as bit vectors.

  3. EnumSet is not synchronized.If multiple threads access an enum set concurrently, and at least one of the threads modifies the set, it should be synchronized externally.

Class declaration

以下是*java.util.EnumSet* 类的声明−

Following is the declaration for java.util.EnumSet class −

public abstract class EnumSet<E extends Enum<E>>
   extends AbstractSet<E>
   implements Cloneable, Serializable

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.AbstractSet

  2. java.util.AbstractCollection

  3. java.util.Object

  4. java.util.Set

Creating an EnumSet Example

以下示例显示了 Java EnumSet 的 of(E) 方法来填充 EnumSet 实例。我们创建了一个枚举 Numbers。然后使用枚举值创建了 EnumSet 实例,并打印了结果 enumSet。

The following example shows the usage of Java EnumSet of(E) method to populate the EnumSet instance. We’ve created a enum Numbers. Then a EnumSet instance is created using a enum value and resulted enumSet is printed.

package com.tutorialspoint;

import java.util.EnumSet;

public class EnumSetDemo {

   // create an enum
   public enum Numbers {
      ONE, TWO, THREE, FOUR, FIVE
   };

   public static void main(String[] args) {

      // create a set that contains an enum
      EnumSet<Numbers> set = EnumSet.of(Numbers.ONE);

      // print set
      System.out.println("Set:" + set);
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Set:[ONE]