Java.util.EnumSet.of() 方法
描述
java.util.EnumSet.of(E first, E... rest) 方法创建一个初始包含指定元素的枚举集。 这个factory,其参数列表使用可变参数特性,可用于创建最初包含任意数量元素的枚举集,但它可能比不使用可变参数的重载运行得更慢。
声明
以下是 java.util.EnumSet.of() 方法的声明
public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest)
参数
first − 集合最初要包含的元素。
rest − 该集合最初要包含的其余元素。
返回值
此方法返回一个初始包含指定元素的枚举集。
异常
NullPointerException − 如果 e 为空
示例
下面的例子展示了 java.util.EnumSet.Of() 方法的使用。
/*This example is using a method called main2
to simulate calling the main method using args
from a command line.*/
package com.tutorialspoint;
import java.util.*;
public class EnumSetDemo {
// create an enum
public enum Numbers {
ONE, TWO, THREE, FOUR, FIVE
};
public static void main(String[] args) {
// create a fake list that will be used like args
Numbers[] list = {Numbers.ONE, Numbers.THREE, Numbers.FOUR, Numbers.FIVE};
// call the fake main
main2(list);
}
// This is a fake main. This is used as an example
public static void main2(Numbers[] fakeargs) {
// create a set
EnumSet<Numbers> set;
// add first element and the rest of fakeargs
set = EnumSet.of(Numbers.ONE, fakeargs);
// print the set
System.out.println("Set:" + set);
}
}
让我们编译并运行上面的程序,这将产生以下结果 −
Set:[ONE, THREE, FOUR, FIVE]

