Java.util.EnumSet.copyOf() Method

Advertisements


Description

The java.util.EnumSet.copyOf(Collection<E> c) method creates an enum set initialized from the specified collection.

Declaration

Following is the declaration for java.util.EnumSet.copyOf() method

public static <E extends Enum<E>> EnumSet<E>> copyOf(Collection<E> c)

Parameters

  • c -- the collection from which to initialize this enum set.

Return Value

This method does not return any value.

Exception

  • IllegalArgumentException-- if c is not an EnumSet instance and contains no elements

  • NullPointerException-- if c is null

Example

The following example shows the usage of java.util.EnumSet.copyOf() method.

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 new collection
      Collection collection = new ArrayList();
	  
      // print the collection
      System.out.println("Colletion :" + collection);

      // add two elements in the collection
      collection.add(Numbers.ONE);
      collection.add(Numbers.THREE);

      // create an EnumSet that is a copy of the collection 
      EnumSet<Numbers> set = EnumSet.copyOf(collection);

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


   }
}

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

Colletion :[ONE, THREE]
Set:[ONE, THREE]



Advertisements
Advertisements