我有一个枚举,其中包含映射到名称和整数的字符串集合。我想根据枚举内的字符串返回整数。
我还将枚举用于其他一些目的,因此我想保留它(否则我将仅使用 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();
最佳答案
只需在 Types
类下创建一个全局 HashMap ,该类存储类型字符串及其相应枚举实例之间的关系。
private static final Map<String, Types> typeMap = new HashMap<String, Types>();
static {
for (Types types : values()) {
typeMap.put(types.type, types);
}
}
public static Types searchByType(String type) {
return typeMap.get(type);
}
关于java - 在枚举内部搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921115/