从Java中的值获取枚举对象.以高效的方式和不使用地图



Enum类中,如何使用其字段值之一获取Enum对象的名称。

public enum Example {
    Object1("val1", "val2"),
    Object2("val3", "val4");
}

我带着val1。我能用它取Object1吗?

如果您可以确保每个Enum常量都有唯一的第一个值,那么对于O(1)复杂性,您可以按照以下方式来实现。我们必须创建内部类来管理val1Example的映射,因为Enum不允许我们在构造函数内的静态映射中添加值。

public enum Example {
    Object1("val1", "val2"), Object2("val3", "val4");
    private static final class ExampleValManager {
        static final Map<String, Example> EXAMPLE_VAL_MANAGER_MAP = new HashMap<>();
    }
    private String val1;
    private String val2;
    private Example(String val1, String val2) {
        this.val1 = val1;
        this.val2 = val2;
        ExampleValManager.EXAMPLE_VAL_MANAGER_MAP.put(val1, this);
    }
    public static Example getExampleByVal1(String val) {
        return ExampleValManager.EXAMPLE_VAL_MANAGER_MAP.get(val);
    }
}

按以下方式使用,

public class Test {
   public static void main(String[] args) {
       System.out.println(Example.getExampleByVal1("val1"));
   }
}

输出

Object1

您实际上没有显示这些字符串对应的任何内容,所以我假设您有名为foobar:的字段

public enum Example {
    final String foo;
    final String bar;
    private Example(String foo, String bar) {
        this.foo = foo;
        this.bar = bar;
    }
}

为了通过foo查找,您只需要一些查找匹配项的方法:

public static Example ofFoo(String foo) {
    for(Example e : Example.values()) {
        if(e.foo.equals(foo))
            return e;
    }
    return null;
}

只要你没有疯狂数量的枚举值,这通常是好的。如果性能实际上是一个问题,您可以将Example.values()缓存在专用静态阵列中,甚至可以设置类似Guava ImmutableMap<String,Example>的东西。

您的enum如下所示:

public enum Example {
    Object1("val1", "val2"),
    Object2("val3", "val4");
    String str1;
    String str2;
    Example(String str1, String str2){
        this.str1 = str1;
        this.str2 = str2;
    }
    static Example getEnumByStr1(String str1){
        for (Example e : values())
            if (e.str1.equals(str1))
                return e;
        return null;
    }
}

您可以通过字符串值获得枚举,然后如下所示:

Example.getNameByStr1("val1");

最新更新