【问题标题】:Getting enum value by passing preset ordinal通过传递预设序数获取枚举值
【发布时间】:2015-12-21 21:51:05
【问题描述】:

我看过这个链接:Convert from enum ordinal to enum type

并尝试获取枚举值。但不工作。我的枚举类是:

public enum OrderStatus {

    OPEN(0),
    DELIVERED(1),
    CANCELLED(3),
    PARTIALLY(4)
}

我将传递缺少 2 的值 0,1,3,4 ,因此它没有这样的顺序。如何在 groovy 或 java 中通过传递 0、1、3 或 4 来获取枚举。

【问题讨论】:

  • 只需在 enum 中声明一个字段,就像在 class 中一样。并提供 constructorgetter method for the field
  • 你能举个例子来描述一下吗?
  • 你所拥有的不是序数,这样称呼只会增加混乱。这是一个常规的旧自定义 int 值
  • 谢谢 blgt,很抱歉造成混乱,

标签: java groovy enums


【解决方案1】:

向枚举添加一个字段,以及一个构造函数:

public enum OrderStatus {
    private Integer codice;

    public Integer getCodice() {
        return codice;
    }

    private OrderStatus(Integer codice) {
        this.codice = codice;
    }

    OPEN(0),
    DELIVERED(1),
    CANCELLED(3),
    PARTIALLY(4)
}

然后你可以像这样定义一个方法:

public static OrderStatus getByCodice(int codice) {
    for (OrderStatus tipo : values()) {
        if (tipo.codice == codice) {
            return tipo;
        }
    }
    throw new IllegalArgumentException("Invalid codice: " + codice);
}

【讨论】:

  • 什么是“tipoEvento”?
  • 对不起,这是一个 OrderStatus 实例,我更正了代码
  • 这里使用Integer而不是int的原因是什么?
  • 没有理由,int 会更合适。但是我从一些有意义的个人项目中获取了代码
  • 我想对这个问题再补充一点,如何在 grails 中将枚举值(即 0、1、3 或 4)而不是枚举字符串保存到数据库中??
【解决方案2】:

记录enum中的值并构建一个Map进行转换。

public enum OrderStatus {

    OPEN(0),
    DELIVERED(1),
    CANCELLED(3),
    PARTIALLY(4);
    final int ordinal;

    private OrderStatus(int ordinal) {
        this.ordinal = ordinal;
    }

    static Map<Integer, OrderStatus> lookup = null;

    public static OrderStatus lookup(int ordinal) {
        // Could just run through the array of values but I will us a Map.
        if (lookup == null) {
            // Late construction - not thread-safe.
            lookup = Arrays.stream(OrderStatus.values())
                    .collect(Collectors.toMap(s -> s.ordinal, s -> s));
        }
        return lookup.get(ordinal);
    }
}

public void test() {
    for (int i = 0; i < 5; i++) {
        System.out.println(i + " -> " + OrderStatus.lookup(i));
    }
}

【讨论】:

  • 你会推荐使用 Map 作为一个有 5 个常量的枚举吗?
  • 如果您需要经常查找,那么可以! O(1)O(n) 之间的差异可能非常显着,即使对于较小的 n,如果经常使用该算法。请记住,以后也可以添加新状态。
  • O(1)O(n) 仅告诉您性能如何缩放 与较大的ns,即如果它从一百万到两百万。对于一个具体的数字,它什么也没说,尤其是对于像5 这样小的数字。事实上,O(n) 算法可能比O(1) 替代方案快得多。但在这里,无论如何,一个更简单的解决方案是可能的。只需在适当位置创建一个包含值的数组或列表(在索引2 处保留null)并使用查找int 作为索引...
  • @OldCurmudgeon:我们也可以使用Function.identity 代替s -&gt; s,因为这样更清楚IMO。
【解决方案3】:

只需像在课堂上一样在枚举中声明一个字段。并为该字段提供一个getter方法:

public enum OrderStatus 
{
    OPEN(0),
    DELIVERED(1), /*pass value*/
    CANCELLED(3),
    PARTIALLY(4);

    private int value; /*Add a field*/

    OrderStatus ( int value )
    {
        this.value = value;
    }

    /*Access with getter*/      
    int getValue ( )
    {
        return value;
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多