Android:enum vs static final ints? [英] Android: enum vs static final ints?
问题描述
有一个枚举
与一组 static final int
的优点(或缺点)在Java Android应用程序?有没有效率或性能优化发生,有利于使用一个或另一个?
What are the advantages (or disadvantages) of having an enum
versus having a set of static final int
s in Java Android applications? Are there efficiency or performance optimizations that occur that favor the use of one or the other?
我在这个上下文中询问这个意图requestCodes和这样的 - 这往往是int在Android示例代码中,与来自C中的枚举值相反。
I ask this in context of say intent requestCodes and such - which tend to be ints in the Android sample code, as opposed to values from an enum, which I was used to in C.
推荐答案
枚举优势此问题:
- 它们比整数,字符串或布尔值
标志的集合更加安全。 - 他们导致更可读的代码。
- 将枚举设置为无效的值比int或
字符串更困难。 - 他们可以轻松地发现一个变量或
参数的允许值。 - 我读过的一切表示它们在C#中的执行方式与整数
一样大多数JVM。
- They are much more type-safe than integers, strings, or sets of boolean flags.
- They lead to more readable code.
- It's more difficult to set an enum to an invalid value than an int or string.
- They make it easy to discover the allowed values for a variable or parameter.
- Everything I've read indicates that they perform just as well as integers in C# and most JVMs.
我会添加:
- 枚举可以有成员和实例变量,而
int
不能。
- Enums can have member and instance variables, whereas an
int
can't.
像大多数抽象一样,它们是一旦他们的表现赶上了。特别是在您的应用程序代码(而不是框架代码)中,我将选择枚举与其他模拟它们的方法。
Like most abstractions, they are generally unequivocally advantageous once their performance catches up. Especially in your application code (as opposed to framework code) I would choose enums over other methods that simulate them.
这篇关于Android:enum vs static final ints?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!