java枚举编译后,什么是Java编译枚举?

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:

Support has been added to serialization to handle enumerated types, which are new in version 5.0. The rules for serializing an enum instance differ from those for serializing an "ordinary" serializable object: the serialized form of an enum instance consists only of its enum constant name, along with information identifying its base enum type. Deserialization behavior differs as well--the class information is used to find the appropriate enum class, and the Enum.valueOf method is called with that class and the received constant name in order to obtain the enum constant to return.

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值