Saturday, 3 May 2014

EnumSet : range (E from, E to)

public static <E extends Enum<E>> EnumSet<E> range(E from, E to)
Creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.

import java.util.*;

class EnumSetRange{
 enum Day{
  MON,TUE,WED,THU,
  FRI,SAT,SUN;
 }
 
 public static void main(String args[]){  
  EnumSet<Day> mySet1;
  mySet1 = EnumSet.range(Day.MON, Day.FRI);
  
  System.out.println("Elements in mySet1 are");
  System.out.println(mySet1);
 }
}

Output
Elements in mySet1 are
[MON, TUE, WED, THU, FRI]

1. throws IllegalArgumentException if from.compareTo(to) > 0
import java.util.*;

class EnumSetRangeIllegal{
 enum Day{
  MON,TUE,WED,THU,
  FRI,SAT,SUN;
 }
 
 public static void main(String args[]){  
  EnumSet<Day> mySet1;
  mySet1 = EnumSet.range(Day.FRI, Day.MON);
  
  System.out.println("Elements in mySet1 are");
  System.out.println(mySet1);
 }
}

Output
Exception in thread "main" java.lang.IllegalArgumentException: FRI > MON
        at java.util.EnumSet.range(EnumSet.java:344)
        at EnumSetRangeIllegal.main(EnumSetRangeIllegal.java:11)

2. throws NullPointerException if from or to are null
import java.util.*;

class EnumSetRangeNull{
 enum Day{
  MON,TUE,WED,THU,
  FRI,SAT,SUN;
 }
 
 public static void main(String args[]){  
  EnumSet<Day> mySet1;
  mySet1 = EnumSet.range(Day.FRI, null);
  
  System.out.println("Elements in mySet1 are");
  System.out.println(mySet1);
 }
}


Output
Exception in thread "main" java.lang.NullPointerException
        at java.lang.Enum.compareTo(Enum.java:178)
        at java.util.EnumSet.range(EnumSet.java:343)
        at EnumSetRangeNull.main(EnumSetRangeNull.java:11)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment