簡體   English   中英

在枚舉內搜索

[英]Searching inside enum

我有一個枚舉,其中包含映射到名稱和整數的字符串的集合。 我想返回基於枚舉內的String的整數。

我也將枚舉用於其他目的,所以我想保留它(否則,我將僅出於此目的使用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類下創建一個全局哈希表即可,該哈希表存儲類型字符串及其對應的枚舉實例之間的關系。

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);
}

您可以使用如下形式:

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

另一種選擇是添加一個private static Map<String, Integer> sizes = new HashMap<>(); Typesput映射放在構造函數中。 然后, 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實例的唯一內置函數是valueOf作為名稱(即,您需要傳遞"A"等)

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM