枚举内的java搜索
我有一个枚举,其中包含映射到名称和整数的字符串集合。我想根据枚举中的字符串返回整数
我还将枚举用于其他目的,因此我希望保留它(否则我将仅使用HashMap)。有可能吗
这是一个例子,展示了我想要实现的目标
public enum Types {
A("a.micro", 1), B("b.small", 2), C("c.medium", 4);
private String type;
private int size;
private Type(String type, int size) {
this.type = type;
this.size = size;
}
public String getType() {
return type;
}
public int getSize() {
return size;
}
}
我想返回基于类型的尺寸:
Type.valueOf("a.micro").getSize();
# 1 楼答案
您可以使用以下内容:
另一种选择是在
Types
内添加private static Map<String, Integer> sizes = new HashMap<>();
映射,并在构造函数内添加put
映射。然后sizeFor(String)
将只进行简单的查找由于
type
是一个自定义成员变量,因此它们没有内置函数。获取Types
实例的唯一内置函数是valueOf
for name(即,您需要传递"A"
等)# 2 楼答案
只需在
Types
类下创建一个全局hashmap,该类存储类型字符串与其对应的枚举实例之间的关系# 3 楼答案
然后,只需调用:
Types.getForType("a.micro").getSize();