从Java中的值获取枚举对象。以高效的方式而不使用地图 [英] Getting Enum Object from its value in Java. In Efficient way and Not using Map

查看:144
本文介绍了从Java中的值获取枚举对象。以高效的方式而不使用地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Enum class, how to get the name of the Enum object using one of its field values.

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

我有 val1 Object1

I have the val1 with me. Can I get Object1 using it ?

推荐答案

如果您可以确保每个枚举常量将具有唯一的第一个值,则遵循 O(1)复杂性。我们必须创建内部类来管理 val1 示例的映射,因为枚举不允许我们在构造函数内的静态地图中添加价值。

You can do it in following way with O(1) complexity if you can assure that every Enum constant will have unique first value. We have to create inner class to manage map of val1 and Example because Enum will not allow us to add value in static map inside the constructor.

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

OUTPUT

Object1

这篇关于从Java中的值获取枚举对象。以高效的方式而不使用地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆