Saturday, 3 May 2014

EnumSet : noneOf

public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType)
Creates an empty enum set with the specified element type.

import java.util.*;

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

Output
Elements in mySet1 are
[]

Adding constant MON

Elements in mySet1 are
[MON]

1. throws NullPointerException if elementType is null
import java.util.*;

class EnumSetNoneOfNull{
 enum Day{
  MON,TUE,WED,THU,
  FRI,SAT,SUN;
 }
 
 public static void main(String args[]){  
  EnumSet<Day> mySet1 = EnumSet.noneOf(null);
 }
}

Output
Exception in thread "main" java.lang.NullPointerException
        at java.lang.System$2.getEnumConstantsShared(System.java:1185)
        at java.util.EnumSet.getUniverse(EnumSet.java:388)
        at java.util.EnumSet.noneOf(EnumSet.java:108)
        at EnumSetNoneOfNull.main(EnumSetNoneOfNull.java:10)

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment