从整数中获取枚举+更多抽象问题



我有一个枚举器,它接受一个int和一个string作为字段。可以通过静态方法或直接从枚举器& instance&;(不熟悉这个词的正确措辞)。我的意思是:

public enum CreatureType {
POKE_PIG(1, "Piggley"), POKE_COW(2, "Cowbert");
private int number;
private String name;
CreatureType(int number, String name) {
this.number = number;
this.name = name;
}
public int getNumber() {
return number;
}
public String getName() {
return name;
}
public static String getName(CreatureType type) {
return type.getName();
}
public static int getNumber(CreatureType type) {
return type.getNumber();
}

但现在我需要得到一个CreatureType从它的int。下面是我写的伪代码,这是我对如何做到这一点的最好猜测:

public static CreatureType getCreatureType(int number) {
switch (number) {
case 1:
return CreatureType.POKE_PIG;
case 2:
return CreatureType.POKE_COW;
default:
break;
}
return null;
}

这感觉很奇怪。我不喜欢这种技术,即使在理论上它应该工作,我觉得必须有一个更好的方式做到这一点。我没有将这些枚举存储在list或set中所以我不能遍历它们,我只是在寻找获取它的正确方法。

您的切换大小写解决方案更有效,但以下代码更容易维护,因为在添加新的enum值时不需要调整:

public static CreatureType getCreatureType(int number) {
for(CreatureType creatureType : CreatureType.values()) {
if(creatureType.number == number) {
return creatureType;
}
}
return null; // No match.
}

最新更新