如果我有一个对象约枚举问题
public class Genre {
private int id;
private int name;
}
和ID和名称都已经提前确定,例如
if (id == 1)
name = "action";
else if (id == 2)
name = "horror";
我的问题是如何建立这两种方法以及
Genre.getName(1); // return "action";
Genre.getId("action"); // return 1;
我想也许我可以用枚举,像
public enum Genre {
ACTION(1), HORROR(2);
private final int id;
private final String name;
private Genre(int id) {
this.id = id;
this.name = getName(id);
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public static String getName(int i) {
switch(i) {
case 1 : return "action";
case 2: return "horror";
default :
return null;
}
}
}
但这种方式,我不知道如何
Genre.getId("action"); // return 1;
而且我怕我无法正常使用枚举。 你能给我一些建议吗?谢谢!
---
起初,我想这样做是什么在我的情况,我想用的ID或名称查找名称或ID喜欢
int id = 1;
Genre.getName(id); // return "action"
或
String name = "action";
Genre.getId(name); // return 1
而且现在感谢所有,我明白为什么我想要做的是建议
int id = 1;
Genre.getGenre(id); // return Genre that id = 1 and the name = "action"
或
String name = "action";
Genre.getGenre(name); // return Genre that id = 1 and the name = "action"
+1代码的好解释。 – amod