EnumSet.range(K, K): This method is available in java.util.EnumSet class of Java.
Syntax:
<K> EnumSet<K> java.util.EnumSet.range(K from, K to)
This method takes two arguments. This method creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.
Parameters: Two parameters are required for this method.
from: the first element in the range.
to: the last element in the range.
Returns: an enum set initially containing all of the elements in the range defined by the two specified endpoints
Throws:
1. NullPointerException - if from or to is null.
2. IllegalArgumentException - if from.compareTo(to) > 0
Approach 1: When no exception
Java
import java.util.EnumSet;public class EnumSetrange {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {Colour from = Colour.RED, to = Colour.YELLOW;System.out.println(EnumSet.range(from, to));}}
Output:
[RED, GREEN, YELLOW]
Approach 2: NullPointerException
Java
import java.util.EnumSet;public class EnumSetrange {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {Colour from = Colour.RED, to = null;System.out.println(EnumSet.range(from, to));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "other" is null at java.base/java.lang.Enum.compareTo(Enum.java:198) at java.base/java.util.EnumSet.range(EnumSet.java:361)
Approach 3: IllegalArgumentException
Java
import java.util.EnumSet;public class EnumSetrange {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {Colour from = Colour.YELLOW, to = Colour.RED;System.out.println(EnumSet.range(from, to));}}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: YELLOW > RED at java.base/java.util.EnumSet.range(EnumSet.java:362)
No comments:
Post a Comment