Maximum number of enum elements in Java

The maximum number of enum elements is 2746. Reading the spec was very misleading and caused me to create a flawed design with the assumption I would never hit the 64K or even 32K high-water mark. Unfortunately, the number is much lower than the spec seems to indicate. As a test, I tried the following with both Java 7 and Java 8: Ran the following code redirecting it to a file, then compiled the resulting .java file.

    System.out.println("public enum EnumSizeTest {");
    int max = 2746;
    for ( int i=0; i<max; i++) {
        System.out.println("VAR"+i+",");
    }
    System.out.println("VAR"+max+"}");

Result, 2746 works, and 2747 does not.

After 2746 entries, the compiler throws a code too large error, like

EnumSizeTest.java:2: error: code too large

Decompiling this Enum class file, the restriction appears to be caused by the code generated for each enum value in the static constructor (mostly).


From the class file format spec:

The per-class or per-interface constant pool is limited to 65535 entries by the 16-bit constant_pool_count field of the ClassFile structure (§4.1). This acts as an internal limit on the total complexity of a single class or interface.

I believe that this implies that you cannot have more then 65535 named "things" in a single class, which would also limit the number of enum constants.

If a see a switch with 2 billion cases, I'll probably kill anyone that has touched that code.

Fortunately, that cannot happen:

The amount of code per non-native, non-abstract method is limited to 65536 bytes by the sizes of the indices in the exception_table of the Code attribute (§4.7.3), in the LineNumberTable attribute (§4.7.8), and in the LocalVariableTable attribute (§4.7.9).