EnumSet.copyOf(Collection) in Java

EnumSet.copyOf(Collection): This method is available in java.util.EnumSet class of Java.

Syntax:

<K> EnumSet<K> java.util.EnumSet.copyOf(Collection<K> c)

This method takes one argument. This method creates an enum set initialized from the specified collection.

Parameters: One parameter is required for this method.

c: the collection from which to initialize this enum set.

Returns: An enum set initialized from the given collection.

Throws:

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

2. NullPointerException - if c is null

Approach 1: When no exception

Java

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;

public class EnumSetcopyOf {
    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        Collection<Colour> collection = new ArrayList<Colour>();

        collection.add(Colour.ORANGE);
        collection.add(Colour.RED);
        System.out.println(EnumSet.copyOf(collection));

    }
}

Output:

[RED, ORANGE]


Approach 2: NullPointerException

Java

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;

public class EnumSetcopyOf {
    public enum Colour {
        RED, GREEN, YELLOW, ORANGE
    };

    public static void main(String[] args) {

        Collection<Colour> collection = new ArrayList<Colour>();

        collection.add(Colour.ORANGE);
        collection.add(Colour.RED);
        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