A coworker and I had a discussion about how Java represents enumerations. I was under the impression they were strictly ints like C/C++. Or, if you add behavior (Type-Safe enum), it gets wrapped in a class. He believed that if it's small enough Java would compact it to a byte.
However, I found this on the Oracle site:
Java programming language enums are far more powerful than their counterparts in other languages, which are little more than glorified integers. The new enum declaration defines a full-fledged class (dubbed an enum type).
I take it they are actual objects then. If so, is there a way to optimize them to save space?
Thanks
Edit: As mentioned in a comment on Jon's answer, I am after the serialization size of an Enum.
No, Java enum values really are objects. They can have fields, methods etc - and different implementations of methods on a per-value basis. However, there's only a fixed set of them - it's not like you create instances of the enum type yourself; the set of valid values is created at type initialization time. Unless you've got a huge number of enum values, it's highly unlikely you need to even think about optimizing.
Note that one bit of optimization which is easy to achieve is using
EnumSet
whenever you're logically considering a set of enum values. This uses a bit pattern to basically represent the set efficiently.(Note that C# is closer to C++ than Java here - the C# enums are sadly non-object-oriented. Sigh.)
EDIT: Enum values are serialized by name according to the documentation:
If you're really after a small serialized form though, you should probably steer clear of Java's built-in serialization anyway, which is relatively verbose (as well as being extremely sensitive to versioning issues). There are all kinds of alternatives - the one I know best is Protocol Buffers, which does serialize enum values as just integers.