java 通过使用特定于该枚举的 int 来设置枚举?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6220842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting an enum by using an int specific to that enum?
提问by JMRboosties
Hey all. So I have a set of enums and a db with integers corresponding to those enums. Something like this, for example:
大家好。所以我有一组枚举和一个与这些枚举对应的整数的数据库。像这样的东西,例如:
public static enum Day {
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);
public final int fId;
private Day(int id) {
this.fId = id;
}
}
I also have a database which only refers to these days by integers, which correspond to their int in the enum set above. What I am looking to do is query a database, which will return an integer, and then set an enumerator to an object based on that integer returned from the db. I could do something like this:
我还有一个数据库,它只用整数来指代这些日子,这些整数对应于上面枚举集中的整数。我想要做的是查询一个数据库,它将返回一个整数,然后根据从 db 返回的整数将一个枚举器设置为一个对象。我可以做这样的事情:
public static Day getDay(int i) {
switch(i) {
case 1:
return Day.SUNDAY;
case 2:
return Day.MONDAY;
//And so on
}
}
But for an enum set with over 100 enums inside this doesn't seem very practical.
但是对于包含超过 100 个枚举的枚举集,这似乎不太实用。
So is there a way to do this? Again my goal is to simply insert an int value and get back an enumerator without having to create a new method for the many enums in this set. Maybe I should just make this its own class rather than an enumerator, but I was hoping to do it this way. Thanks!
那么有没有办法做到这一点?同样,我的目标是简单地插入一个 int 值并返回一个枚举器,而不必为这个集合中的许多枚举创建一个新方法。也许我应该让它成为自己的类而不是枚举器,但我希望这样做。谢谢!
采纳答案by David Z
Enums have a built-in ID number, the "ordinal," that you can use for this purpose, as long as you have an easy way to get from the number that represents a given value in the database to the ordinal of the enum. Ordinals are assigned to enum values in the order they are declared in the source file, starting from 0, so in your example, SUNDAY
would have an ordinal of 0, MONDAY
of 1, etc.
枚举有一个内置的 ID 号,即“序数”,您可以将其用于此目的,只要您有一种简单的方法从代表数据库中给定值的数字到枚举的序数。序号按照它们在源文件中声明的顺序分配给枚举值,从 0 开始,因此在您的示例中,SUNDAY
序号为 0、1MONDAY
等。
In order to use this, you just have to convert the integer stored in the database to its corresponding ordinal, and then use it to access the enum value. So for your example, an implementation might be
为了使用它,您只需要将存储在数据库中的整数转换为其相应的序数,然后使用它来访问枚举值。所以对于你的例子,一个实现可能是
private static Day[] values = Day.values();
public static Day getDay(int i) {
return values[i - 1];
}
If the order of the enum values according to their database IDs is the same order with which they are declared in the source code, then you can pretty much just use the above method as-is (except for changing the class name). Otherwise, you may have to do something a little more complicated to map database values to ordinals; perhaps setting up an array, if the mapping is highly nonlinear.
如果枚举值根据它们的数据库 ID 的顺序与它们在源代码中声明的顺序相同,那么您几乎可以按原样使用上述方法(除了更改类名)。否则,您可能需要做一些更复杂的事情来将数据库值映射到序数;如果映射是高度非线性的,可能会设置一个数组。
P.S. And of course if you do this, there would be no use for the fId
field.
PS 当然,如果您这样做,该fId
领域将毫无用处。
回答by Bohemian
Here's a simple implementation that will work:
这是一个可以工作的简单实现:
public static enum Day {
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);
public final int fId;
private Day(int id) {
this.fId = id;
}
public static Day forInt(int id) {
for (Day day : values()) {
if (day.fId == id) {
return day;
}
}
throw new IllegalArgumentException("Invalid Day id: " + id);
}
}
If you know that your enums start counting from 1, you can simply use this instead:
如果您知道您的枚举从 1 开始计数,您可以简单地使用它:
public static Day forInt(int id) {
return values()[id - 1];
}
回答by Basanth Roy
You enum class should have a lookup map built inside as a static variable. Hence your enum class should be something like.
您的枚举类应该在内部构建一个查找映射作为静态变量。因此你的枚举类应该是这样的。
public static enum Day {
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);
public final int fId;
private Day(int id) {
this.fId = id;
}
private static final Map<Integer, Day > lookup
= new HashMap<Integer, Day >();
static {
for (Day s : EnumSet.allOf(Day.class))
lookup.put(s.getIntValue(), s);
}
public static Day getValue(int intValue) {
return lookup.get(intValue);
}
}
Then to retrieve the correct enum based on an int i, you can just invoke
然后要根据 int i 检索正确的枚举,您只需调用
Day.getValue(i);
This approach will work even if the numbering is non-linear or has gaps in it.
即使编号是非线性的或有间隙,这种方法也能奏效。
回答by bigoldbrute
Edited- cache created lazy.
编辑- 缓存创建懒惰。
You can create Map<Integer,Day>
runtime and use that in getDay implementation.
您可以创建Map<Integer,Day>
运行时并在 getDay 实现中使用它。
public static enum Day {
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);
private static Map<Integer,Day> CACHE = null;
private static void lazyFillCache() {
if (CACHE != null) return;
final Map<Integer,Day> c = new HashMap<Integer,Day>();
for (final Day d : Day.values()) {
c.put(d.fId, d);
}
CACHE = c;
}
public static Day getDay(int i) {
lazyFillCache();
return CACHE.get(i);
}
public final int fId;
private Day(int id) {
this.fId = id;
}
}
Edit- Inspired by Tom Hawtins comment here, you can also use this implementation, which takes advantage of Java class loading capabilities:
编辑-由汤姆Hawtins评论的启发在这里,你还可以使用此实现,它利用了Java类加载功能:
public static enum Day {
SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5), FRIDAY(6), SATURDAY(7);
private static class Cache {
private static Map<Integer,Day> CACHE = new HashMap<Integer,Day>();
static {
for (final Day d : Day.values()) {
CACHE.put(d.fId, d);
}
}
}
public static Day getDay(int i) {
return Cache.CACHE.get(i);
}
public final int fId;
private Day(int id) {
this.fId = id;
}
}
回答by MRAB
Day.values() will return a (zero-based) array of the enum values.
Day.values() 将返回枚举值的(从零开始的)数组。
回答by Ivo Stoyanov
Day myDay = Day.values()[x] - x is the int value
Day myDay = Day.values()[x] - x 是 int 值