📜  Java中的枚举集

📅  最后修改于: 2022-05-13 01:55:00.596000             🧑  作者: Mango

Java中的枚举集

枚举或通常称为枚举的目的是在编程语言中表示一组命名常量。例如,一副扑克牌中的 4 个花色可能是 4 个枚举器,名称为 Club、Diamond、Heart 和 Spade,属于一个名为 Suit 的枚举类型。

EnumSet是用于枚举类型的 Set 接口的特殊实现之一。 EnumSet 的几个重要特性如下:

  • 它扩展了 AbstractSet 类并在Java中实现了 Set 接口。
  • EnumSet 类是Java集合框架的成员,并且不同步。
  • 它是一个高性能的集合实现,比 HashSet 快得多。
  • EnumSet 中的所有元素必须来自一个枚举类型,该枚举类型在显式或隐式创建集合时指定。
  • 如果我们这样做,它不允许空对象并抛出 NullPointerException。
  • 它使用故障安全迭代器,因此不会抛出 ConcurrentModificationException 如果集合在迭代时被修改。

EnumSet 的层次结构如下:

java.lang.Object
   ↳ java.util.AbstractCollection
        ↳ java.util.AbstractSet
             ↳ java.util.EnumSet

这里, E是存储元素的类型。

Java 集合中的 EnumSet

语法:声明

public abstract class EnumSet> 

这里, E指定元素。 E 必须扩展 Enum,它强制要求元素必须是指定的枚举类型。

使用 EnumSet 的好处

  • 由于它使用RegularEnumSetJumboEnumSet 实现, EnumSet 中的所有方法都是使用按位算术运算实现的。
  • EnumSet 比 HashSet 快,因为我们不需要计算任何 hashCode 来找到正确的桶。
  • 计算在恒定时间内执行,所需空间非常小。

EnumSet 的方法

Method

Action Performed 

allOf​(Class elementType)Creates an enum set containing all of the elements in the specified element type.
clone()Returns a copy of this set.
complementOf​(EnumSet s)Creates an enum set with the same element type as the specified enum set, initially containing all the elements of this type that are not contained in the specified set.
copyOf​(Collection c)Creates an enum set initialized from the specified collection.
copyOf​(EnumSet s)Creates an enum set with the same element type as the specified enum set, initially containing the same elements (if any).
noneOf​(Class elementType)Creates an empty enum set with the specified element type.
of​(E e)Creates an enum set initially containing the specified element.
of​(E e1, E e2)Creates an enum set initially containing the specified elements.
of​(E first, E… rest)Creates an enum set initially containing the specified elements.
of​(E e1, E e2, E e3)Creates an enum set initially containing the specified elements.
of​(E e1, E e2, E e3, E e4)Creates an enum set initially containing the specified elements.
of​(E e1, E e2, E e3, E e4, E e5)Creates an enum set initially containing the specified elements.
range​(E from, E to)Creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.

执行:

Java
// Java Program to Illustrate Working
// of EnumSet and its functions
 
// Importing required classes
import java.util.EnumSet;
 
// Enum
enum Gfg { CODE, LEARN, CONTRIBUTE, QUIZ, MCQ };
 
// Main class
// EnumSetExample
public class GFG {
 
    // Main driver method
    public static void main(String[] args) {
 
        // Creating a set
        EnumSet set1, set2, set3, set4;
 
        // Adding elements
        set1 = EnumSet.of(Gfg.QUIZ, Gfg.CONTRIBUTE,
                          Gfg.LEARN, Gfg.CODE);
        set2 = EnumSet.complementOf(set1);
        set3 = EnumSet.allOf(Gfg.class);
        set4 = EnumSet.range(Gfg.CODE, Gfg.CONTRIBUTE);
 
        // Printing corresponding elements in Sets
        System.out.println("Set 1: " + set1);
        System.out.println("Set 2: " + set2);
        System.out.println("Set 3: " + set3);
        System.out.println("Set 4: " + set4);
    }
}


Java
// Java Program to illustrate Creation an EnumSet
 
// Importing required classes
import java.util.*;
 
// Main class
// CreateEnumSet
class GFG {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumSet using allOf()
        EnumSet games = EnumSet.allOf(Game.class);
 
        // Printing EnumSet elements to the console
        System.out.println("EnumSet: " + games);
    }
}


Java
// Java program to illustrate Addition of Elements
// to an EnumSet
 
// Importing required classes
import java.util.EnumSet;
 
// Main class
class AddElementsToEnumSet {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumSet
        // using allOf()
        EnumSet games1 = EnumSet.allOf(Game.class);
 
        // Creating an EnumSet
        // using noneOf()
        EnumSet games2 = EnumSet.noneOf(Game.class);
 
        // Using add() method
        games2.add(Game.HOCKEY);
 
        // Printing the elements to the console
        System.out.println("EnumSet Using add(): "
                           + games2);
 
        // Using addAll() method
        games2.addAll(games1);
 
        // Printing the elements to the console
        System.out.println("EnumSet Using addAll(): "
                           + games2);
    }
}


Java
// Java program to Access Elements of EnumSet
 
// Importing required classes
import java.util.EnumSet;
import java.util.Iterator;
 
// Main class
// AccessingElementsOfEnumSet
class GFG {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // MAin driver method
    public static void main(String[] args)
    {
        // Creating an EnumSet using allOf()
        EnumSet games = EnumSet.allOf(Game.class);
 
        // Creating an iterator on games
        Iterator iterate = games.iterator();
 
        // Display message
        System.out.print("EnumSet: ");
 
        while (iterate.hasNext()) {
 
            // Iterating and printing elements to
            // the console using next() method
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}


Java
// Java program to Remove Elements
// from a EnumSet
 
// Importing required classes
import java.util.EnumSet;
 
// Main class
// RemovingElementsOfEnumSet
class GFG {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating EnumSet using allOf()
        EnumSet games = EnumSet.allOf(Game.class);
 
        // Printing the EnumSet
        System.out.println("EnumSet: " + games);
 
        // Using remove()
        boolean value1 = games.remove(Game.CRICKET);
 
        // Printing elements to the console
        System.out.println("Is CRICKET removed? " + value1);
 
        // Using removeAll() and storing the boolean result
        boolean value2 = games.removeAll(games);
 
        // Printing elements to the console
        System.out.println("Are all elements removed? "
                           + value2);
    }
}


输出
Set 1: [CODE, LEARN, CONTRIBUTE, QUIZ]
Set 2: [MCQ]
Set 3: [CODE, LEARN, CONTRIBUTE, QUIZ, MCQ]
Set 4: [CODE, LEARN, CONTRIBUTE]

操作一:创建 EnumSet 对象

由于 EnumSet 是一个抽象类,我们不能直接创建它的实例。它有许多允许我们创建实例的静态工厂方法。 JDK提供了两种不同的EnumSet实现

  • 正则枚举集
  • 巨型枚举集  

RegularEnumSet使用单个长对象来存储 EnumSet 的元素。 long 元素的每一位代表一个 Enum 值。由于 long 的大小为 64 位,因此它最多可以存储 64 个不同的元素。

JumboEnumSet使用长元素数组来存储 EnumSet 的元素。与 RegularEnumSet 的唯一区别是 JumboEnumSet 使用长数组来存储位向量,从而允许超过 64 个值。

工厂方法根据元素数量创建实例,EnumSet 不提供任何公共构造函数,使用静态工厂方法创建实例,如下所示:

  • 全部(大小)
  • 无(大小)
  • 范围(e1,e2)
  • 的()            

插图:

if (universe.length <= 64)
    return new RegularEnumSet<>(elementType, universe);
else
    return new JumboEnumSet<>(elementType, universe);

例子:

Java

// Java Program to illustrate Creation an EnumSet
 
// Importing required classes
import java.util.*;
 
// Main class
// CreateEnumSet
class GFG {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumSet using allOf()
        EnumSet games = EnumSet.allOf(Game.class);
 
        // Printing EnumSet elements to the console
        System.out.println("EnumSet: " + games);
    }
}
输出
EnumSet: [CRICKET, HOCKEY, TENNIS]

操作2:添加元素

我们可以使用 add() 和 addAll() 方法向 EnumSet 添加元素。

例子:

Java

// Java program to illustrate Addition of Elements
// to an EnumSet
 
// Importing required classes
import java.util.EnumSet;
 
// Main class
class AddElementsToEnumSet {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an EnumSet
        // using allOf()
        EnumSet games1 = EnumSet.allOf(Game.class);
 
        // Creating an EnumSet
        // using noneOf()
        EnumSet games2 = EnumSet.noneOf(Game.class);
 
        // Using add() method
        games2.add(Game.HOCKEY);
 
        // Printing the elements to the console
        System.out.println("EnumSet Using add(): "
                           + games2);
 
        // Using addAll() method
        games2.addAll(games1);
 
        // Printing the elements to the console
        System.out.println("EnumSet Using addAll(): "
                           + games2);
    }
}
输出
EnumSet Using add(): [HOCKEY]
EnumSet Using addAll(): [CRICKET, HOCKEY, TENNIS]

操作3:访问元素

我们可以使用iterator() 方法访问 EnumSet 元素。

例子:

Java

// Java program to Access Elements of EnumSet
 
// Importing required classes
import java.util.EnumSet;
import java.util.Iterator;
 
// Main class
// AccessingElementsOfEnumSet
class GFG {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // MAin driver method
    public static void main(String[] args)
    {
        // Creating an EnumSet using allOf()
        EnumSet games = EnumSet.allOf(Game.class);
 
        // Creating an iterator on games
        Iterator iterate = games.iterator();
 
        // Display message
        System.out.print("EnumSet: ");
 
        while (iterate.hasNext()) {
 
            // Iterating and printing elements to
            // the console using next() method
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}
输出
EnumSet: CRICKET, HOCKEY, TENNIS,

操作4:移除元素

我们可以使用 remove() 和 removeAll() 方法删除元素。

例子:

Java

// Java program to Remove Elements
// from a EnumSet
 
// Importing required classes
import java.util.EnumSet;
 
// Main class
// RemovingElementsOfEnumSet
class GFG {
 
    // Enum
    enum Game { CRICKET, HOCKEY, TENNIS }
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating EnumSet using allOf()
        EnumSet games = EnumSet.allOf(Game.class);
 
        // Printing the EnumSet
        System.out.println("EnumSet: " + games);
 
        // Using remove()
        boolean value1 = games.remove(Game.CRICKET);
 
        // Printing elements to the console
        System.out.println("Is CRICKET removed? " + value1);
 
        // Using removeAll() and storing the boolean result
        boolean value2 = games.removeAll(games);
 
        // Printing elements to the console
        System.out.println("Are all elements removed? "
                           + value2);
    }
}
输出
EnumSet: [CRICKET, HOCKEY, TENNIS]
Is CRICKET removed? true
Are all elements removed? true

下面定义了一些其他类或接口的方法,它们以某种方式帮助我们更好地理解 AbstractSet 类,如下所示:

在类Java.util.AbstractSet 中声明的方法

METHOD

DESCRIPTION

equals​(Object o)Compares the specified object with this set for equality.
 hashCode()Returns the hash code value for this set.
removeAll​(Collection c)Removes from this set all of its elements that are contained in the specified collection (optional operation).

在接口Java.util.Collection 中声明的方法

METHOD

DESCRIPTION

parallelStream()Returns a possibly parallel Stream with this collection as its source.
removeIf​(Predicate filter)Removes all of the elements of this collection that satisfy the given predicate.
stream()Returns a sequential Stream with this collection as its source.
toArray​(IntFunction generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.

在接口Java.lang.Iterable 中声明的方法

METHOD

DESCRIPTION

forEach​(Consumer action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

在接口Java.util.Set 中声明的方法

METHOD

DESCRIPTION

add​(E e)Adds the specified element to this set if it is not already present (optional operation). 
addAll​(Collection c) Adds the specified element to this set if it is not already present (optional operation).
 clear()Removes all of the elements from this set (optional operation).
 contains​(Object o)Returns true if this set contains the specified element. 
containsAll​(Collection c) Returns true if this set contains all of the elements of the specified collection.
 isEmpty()Returns true if this set contains no elements.
 iterator()Returns an iterator over the elements in this set.
remove​(Object o)Removes the specified element from this set if it is present (optional operation).
retainAll​(Collection c) Retains only the elements in this set that are contained in the specified collection (optional operation).
size()Returns the number of elements in this set (its cardinality).
spliterator()Creates a Spliterator over the elements in this set.
toArray()Returns an array containing all of the elements in this set.
toArray​(T[] a)Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

在类Java.util.AbstractCollection 中声明的方法

METHOD

DESCRIPTION

 add​(E e)Ensures that this collection contains the specified element (optional operation).
 addAll​(Collection c)Adds all of the elements in the specified collection to this collection (optional operation).
clear()Removes all of the elements from this collection (optional operation).
contains​(Object o)Returns true if this collection contains the specified element.
containsAll​(Collection c)Returns true if this collection contains all of the elements in the specified collection.
isEmpty()Returns true if this collection contains no elements.
iterator()Returns an iterator over the elements contained in this collection.
remove​(Object o)Removes a single instance of the specified element from this collection, if it is present (optional operation).
retainAll​(Collection c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
 toArray()Returns an array containing all of the elements in this collection.
toArray​(T[] a)Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
 toString()Returns a string representation of this collection.