Saturday 3 May 2014

EnumSet : allOf : Creates an enum set

public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType)
Creates an enum set containing all of the elements in the specified element type.

enum Day{
 MON,
 TUE,
 WED,
 THU,
 FRI,
 SAT,
 SUN;
}

import java.util.*;

class EnumSetAllOf{
 public static void main(String args[]){
  EnumSet<Day> mySet = EnumSet.allOf(Day.class);
  
  Iterator<Day> iter = mySet.iterator();
  
  while(iter.hasNext()){
   System.out.println(iter.next());
  }
 }
}

Output
MON
TUE
WED
THU
FRI
SAT
SUN

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

class EnumSetAllOfNull{
 public static void main(String args[]){
  EnumSet<Day> mySet = EnumSet.allOf(null);
  
  Iterator<Day> iter = mySet.iterator();
  
  while(iter.hasNext()){
   System.out.println(iter.next());
  }
 }
}

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 java.util.EnumSet.allOf(EnumSet.java:127)
        at EnumSetAllOfNull.main(EnumSetAllOfNull.java:5)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment