EnumSet.copyOf(EnumSet): This method is available in java.util.EnumSet class of Java.
Syntax:
<K> EnumSet<K> java.util.EnumSet.copyOf(EnumSet<K> s)
This method takes one argument. This method creates an enum set with the same element type as the specified enumset, initially containing the same elements
Parameters: One parameter is required for this method.
s: the enum set from which to initialize this enum set.
Returns: A copy of the specified enum set.
Throws:
NullPointerException - if s is null
Approach 1: When no exception
Java
import java.util.EnumSet;public class EnumSetcopyOf2 {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {EnumSet<Colour> enumSet = EnumSet.allOf(Colour.class);System.out.println(EnumSet.copyOf(enumSet));}}
Output:
[RED, GREEN, YELLOW, ORANGE]
Approach 2: NullPointerException
Java
import java.util.EnumSet;public class EnumSetcopyOf2 {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {System.out.println(EnumSet.copyOf(null));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.EnumSet.clone()" because "s" is null at java.base/java.util.EnumSet.copyOf(EnumSet.java:153)
No comments:
Post a Comment