枚举和字符串之间的java映射?
所以,我最近读了this post,我想有效地做同样的事情
我真的不在乎“丑”,所以我实施了以下方法之一:
public enum Day {
Monday(1),
Tuesday(2),
Wednesday(3),
Thursday(4),
Friday(5),
Saturday(6),
Sunday(7);
public final int id;
Day(int id) {
this.id = id;
}
public static Day getByID(int id) {
Day d = null;
for (Day dTemp : Day.values())
{
if (id == dTemp)
{
d = dTemp;
break;
}
}
return d;
}
public Day getNext() {
return values()[(ordinal()+1)%values().length];
}
public Day getPrev() {
return values()[(ordinal()-1)%values().length];
}
}
但是,当我这样做时,它的问题在于if语句:
if (id == dTemp)
它说它们是不兼容的类型。我该怎么做才能修好它
# 1 楼答案
应该有用
或者尝试使用
enum
的ordinal()
方法我复制了你的代码并进行了相应的测试
两者都有
及
工作正常,生产如期。声明
制作周一
# 2 楼答案
使用
if ( id == dTemp.id )
。枚举是类,枚举值是对象而不是int,因此不能(显式或隐式)强制转换到int
或者,请注意,枚举有一个序号,即其位置的id。在您的示例中,
Monday
将有序号0,Sunday
将有序号6。您可以通过调用ordinal()
方法来访问序号因此,如果
id
是一个基础,那么您可以执行以下操作:请注意,您可能希望在私有静态变量中缓存
Day.values()
,然后访问缓存的数组顺便问一下,你在问题中提到的字符串在哪里