Question

I found that a limit number of enumeration (64) is used in EnumSet. Please see a method in EnumSet source code below (This code is captured from JDK 1.7).

/**
 * Creates an empty enum set with the specified element type.
 *
 * @param elementType the class object of the element type for this enum
 *     set
 * @throws NullPointerException if <tt>elementType</tt> is null
 */
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);
} 

From the above code we can see: if the length of Enum array is less than 64, RegularEnumSet is used. Otherwise, JumboEnumSet is used instead.

Here my questions are as follows:

  1. How does this limit number of enumeration (64) comes from or how to calculate it as 64?
  2. Why RegularEnumSet and JumboEnumSet are both used, What good is there in doing that?
Was it helpful?

Solution

It's not limited to 64. There is a just a different implementation chosen if there are more than 64 items. I haven't looked at the source, but I would guess that a RegularEnumSet is implemented as a bit mask using a single long.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top