查找枚举大小的更好方法是什么?
可能的重复:
枚举值().length与私有字段
我想知道哪个这些查找枚举大小的方法更好。
这样:
public enum Company {
AUDI(4), BMW(5), CADILLAC(11), FORD(44), JAGUAR(45);
private final int id;
public final int length = Company.values().length;
private Company(int id) {
this.id = id;
}
}
或者这样:
public enum Company {
AUDI(4), BMW(5), CADILLAC(11), FORD(44), JAGUAR(45);
private final int id;
public final int length = 5;
private Company(int id) {
this.id = id;
}
}
Possible Duplicate:
Enum values().length vs private field
I want to know how which of these ways to find the size of the enum is better.
This way:
public enum Company {
AUDI(4), BMW(5), CADILLAC(11), FORD(44), JAGUAR(45);
private final int id;
public final int length = Company.values().length;
private Company(int id) {
this.id = id;
}
}
Or this way:
public enum Company {
AUDI(4), BMW(5), CADILLAC(11), FORD(44), JAGUAR(45);
private final int id;
public final int length = 5;
private Company(int id) {
this.id = id;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
给定 -
小部件的大小是:
given -
the size of Widgets is:
第一个,但将其设置为
静态
,这样就不会创建数组的多个副本。The first one, but make it
static
so you don't make multiple copies of the array.都不是。只需在需要的地方使用 myEnum.values().size 即可。
Neither way. Just use myEnum.values().size where you need it.
在我看来,第一种方式更好。这样,如果您向枚举添加更多公司,则无需手动更新长度变量。
In my opinion, the first way is better. This way, you don't have to manually update the length variable if you add more companies to the enum.
第二种方法的问题是,每次添加新值时,都必须手动更新长度。
对于第一种方法,它是动态的,您甚至可以将其设置为静态(因为如果不这样做,它将为每个枚举实例获取一个整数):
但我建议使用“Company.values().length”,因为它更标准。
The problem with the second way is that every time you add a new value, you have to update the length manually.
For the first method, it's dynamic and you can even put it static (since it will take an integer per enum instance if you don't):
But I would suggest using 'Company.values().length' since it's more standard.