Special Classes to Process Enums

text zoom

Two classes have been added to java.util in support of enums. The classes are EnumSet and EnumMap. EnumSet is a special purpose Set implementation whereas the EnumMap is the Map implementation of Enums.All of the members of an enum set must be of the same enum type.


 


Consider the Enums of Day from the previous examples. If user want to it iterate only a part of Enums it is not possible. EnumSet will give a range method to support this type of feature. The below example will demonstrate the use of EnumSet class.


 


Example:-


 


package com.visualbuilder;


 


import java.util.EnumSet;


 


public class EnumSetExample {
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}


public static void main(String[] args) {


    for (Day obj : EnumSet.range(Day.TUESDAY, Day.FRIDAY)) {
                System.out.println(obj.toString());
        }
    }
}


Output:-


 


The following output will be displayed on the screen.


TUESDAY
WEDNESDAY
THURSDAY
FRIDAY


 


Note:- Similarly, EnumMap is a high-performance Map implementation for use with enum keys, internally implemented as an array. Enum maps combine the richness and safety of the Map interface with speed approaching that of an array. If you want to map an enum to a value, you should always use an EnumMap in preference to an array.

                    

Copyright © 2010 VisualBuilder. All rights reserved