Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum number of enum elements in Java

What is the maximum number of elements allowed in an enum in Java?

I wanted to find out the maximum number of cases in a switch statement. Since the largest primitive type allowed in switch is int, we have cases from -2,147,483,648 to 2,147,483,647 and one default case. However enums are also allowed... so the question..

like image 391
Rnet Avatar asked Dec 17 '10 06:12

Rnet


People also ask

What is the size of enum in Java?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.

How many values can enum hold?

An ENUM column can have a maximum of 65,535 distinct elements. If you retrieve an ENUM value in a numeric context, the column value's index is returned.

Why are enums all caps?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.


1 Answers

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).

like image 147
Thilo Avatar answered Sep 21 '22 23:09

Thilo