📜  Java EnumSet类

📅  最后修改于: 2020-10-13 00:32:10             🧑  作者: Mango

Java EnumSet类

Java EnumSet类是用于枚举类型的专用Set实现。它继承AbstractSet类并实现Set接口。

EnumSet类层次结构

EnumSet类的层次结构在下图中给出。

EnumSet类声明

我们来看一下java.util.EnumSet类的声明。

public abstract class EnumSet> extends AbstractSet implements Cloneable, Serializable

Java EnumSet类的方法

Method Description
static > EnumSet allOf(Class elementType) It is used to create an enum set containing all of the elements in the specified element type.
static > EnumSet copyOf(Collection c) It is used to create an enum set initialized from the specified collection.
static > EnumSet noneOf(Class elementType) It is used to create an empty enum set with the specified element type.
static > EnumSet of(E e) It is used to create an enum set initially containing the specified element.
static > EnumSet range(E from, E to) It is used to create an enum set initially containing the specified elements.
EnumSet clone() It is used to return a copy of this set.

Java EnumSet示例

import java.util.*;
enum days {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
  public static void main(String[] args) {
    Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);
    // Traversing elements
    Iterator iter = set.iterator();
    while (iter.hasNext())
      System.out.println(iter.next());
  }
}

输出:

TUESDAY
WEDNESDAY

Java EnumSet示例:allOf()和noneOf()

import java.util.*;
enum days {
  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
  public static void main(String[] args) {
    Set set1 = EnumSet.allOf(days.class);
      System.out.println("Week Days:"+set1);
      Set set2 = EnumSet.noneOf(days.class);
      System.out.println("Week Days:"+set2);   
  }
}

输出:

Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY]
Week Days:[]