javaenumset

Which class in Java implements the abstract class EnumSet?


I see that EnumSet.of() returns an instance of an object of the type EnumSet. But I am not able to figure out which class actually implements this abstract class? How can you get an instance of the abstract type EnumSet, when you have not subclassed it?


Solution

  • Here is are 2 classes in java which extends EnumSet

    1. RegularEnumSet
    2. JumboEnumSet
    

    You can create the instance using EnumSet's static methods like EnumSet#noneOf, EnumSet#allOf etc. Which actually returns the instance of RegularEnumSet or JumboEnumSet depending on the condition. EnumSet#of internally calls EnumSet#noneOf.Please refer the below code from Java to see how EnumSet#noneOf works

    public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) {
        Enum<?>[] universe = getUniverse(elementType);
        if (universe == null)
            throw new ClassCastException(elementType + " not an enum");
    
        if (universe.length <= 64)
            return new RegularEnumSet<>(elementType, universe);
        else
            return new JumboEnumSet<>(elementType, universe);
    }