Saturday, 3 May 2014

EnumSet : of(E first, E... rest)

public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest)
Creates an enum set initially containing the specified elements. It uses varargs, so arbitrary number of arguments can be passed. It is likely to run slower than the overloadings that do not use varargs.

import java.util.*;

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

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

1. throws NullPointerException if any of the specified elements are null
import java.util.*;

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

Output
Exception in thread "main" java.lang.NullPointerException
        at java.util.EnumSet.typeCheck(EnumSet.java:378)
        at java.util.RegularEnumSet.add(RegularEnumSet.java:160)
        at java.util.RegularEnumSet.add(RegularEnumSet.java:36)
        at java.util.EnumSet.of(EnumSet.java:325)
        at EnumSetOfVarargNull.main(EnumSetOfVarargNull.java:11)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment