Java 将枚举编译成什么?
我和一位同事讨论了 Java 如何表示枚举。我的印象是它们是严格的整数,就像 C/C++ 一样。或者,如果您添加行为(类型安全枚举),它将被包装在一个类中。他相信如果它足够小,Java 会将其压缩为一个字节。
然而,我在 Oracle 网站上发现了这一点:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,Java 枚举值确实是对象。它们可以具有字段、方法等 - 以及基于每个值的不同方法实现。但是,它们只有一组固定的 - 这不像您自己创建枚举类型的实例;有效值集是在类型初始化时创建的。除非您有大量的枚举值,否则您几乎不需要考虑优化。
请注意,很容易实现的一点优化是使用
EnumSet
每当您从逻辑上考虑一组枚举值时。这使用位模式来基本上有效地表示集合。(请注意,这里 C# 比 Java 更接近 C++ - 遗憾的是 C# 枚举是非面向对象的。唉。)
编辑:枚举值根据 文档:
如果您确实想要一个小的序列化形式,那么您可能应该避开 Java 的内置序列化,因为它相对冗长(并且对版本控制问题极其敏感)。有各种各样的替代方案 - 我最了解的一个是协议缓冲区,它确实将枚举值序列化为整数。
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.