當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.util.EnumSet.of()用法及代碼示例


描述

這個java.util.EnumSet.of(E first, E... rest)方法創建一個最初包含指定元素的枚舉集。這個工廠,其參數列表使用可變參數特性,可用於創建一個最初包含任意數量元素的枚舉集,但它可能比不使用可​​變參數的重載運行得更慢。

聲明

以下是聲明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]

相關用法


注:本文由純淨天空篩選整理自 Java.util.EnumSet.of() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。