有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

枚举内的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();

共 (3) 个答案

  1. # 1 楼答案

    您可以使用以下内容:

    public static int sizeFor(String name) {
        for(Types type : Types.values()) {
            if(type.getType().equals(name)) {
                return type.getSize();
            }
        }
        // handle invalid name
        return 0;
    }
    

    另一种选择是在Types内添加private static Map<String, Integer> sizes = new HashMap<>();映射,并在构造函数内添加put映射。然后sizeFor(String)将只进行简单的查找

    private static Map<String, Integer> sizes = new HashMap<>();
    
    Type(String type, int size) {
        this.type = type;
        this.size = size;
        sizes.put(type, size);
    }
    
    public static int sizeFor(String name) {
        // Modify if you need to handle missing names differently
        return sizes.containsKey(name) ? sizes.get(name) : 0;
    }  
    

    由于type是一个自定义成员变量,因此它们没有内置函数。获取Types实例的唯一内置函数是valueOffor name(即,您需要传递"A"等)

  2. # 2 楼答案

    只需在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);
    }
    
  3. # 3 楼答案

    public enum Type {
    
        A("a.micro", 1), B("b.small", 2), C("c.medium", 4);
    
        private static final Map<String, Type> map = createMap();
    
        private static Map<String, Type> createMap() {
            Map<String, Type> result = new HashMap<>();
            for (Type type : values()) {
                result.put(type.type, type);
            }
            return null;
        }
    
        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;
        }
    
        public static Type getForType(String type) {
            return map.get(type);
        }
    }
    

    然后,只需调用:Types.getForType("a.micro").getSize();