优化java枚举

1 java enums

我的代码包含多个枚举,如下所示。基本上这有助于通过整数而不是枚举值使用枚举。是否可以应用某种优化,例如继承或其他东西,以便所有人都可以具有如下所示的行为。

public enum DeliveryMethods {

    STANDARD_DOMESTIC(1), STANDARD_INTERNATIONAL(2), EXPRESS_DOMESTIC(3), EXPRESS_INTERNATIONAL(4);

    private final int code;

    private DeliveryMethods(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    private static final HashMap<Integer, DeliveryMethods> valueMap = new HashMap<>(2);

    static {
        for (DeliveryMethods type : DeliveryMethods.values()) {
            valueMap.put(type.code, type);
        }
    }

    public static DeliveryMethods getValue(int code) {
        return valueMap.get(code);
    }
}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 5

这是一个示例,展示了如何委托给另一个类:

public interface Keyed<K> {
    /**
     * returns the key of the enum
     */
    K getKey();
}

public class KeyEnumMapping<K, E extends Enum<?> & Keyed<K>> {
    private Map<K, E> map = new HashMap<>();

    public KeyEnumMapping(Class<E> clazz) {
        E[] enumConstants = clazz.getEnumConstants();
        for (E e : enumConstants) {
            map.put(e.getKey(), e);
        }
    }

    public E get(K key) {
        return map.get(key);
    }
}

public enum Example implements Keyed<Integer> {
    A(1),
    B(3),
    C(7);

    private static final KeyEnumMapping<Integer, Example> MAPPING = new KeyEnumMapping<>(Example.class);
    private Integer value;

    Example(Integer value) {
        this.value = value;
    }

    @Override
    public Integer getKey() {
        return value;
    }

    public static Example getByValue(Integer value) {
        return MAPPING.get(value);
    }

    public static void main(String[] args) {
        System.out.println(Example.getByValue(3));
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以避免实现Function<E, K>Keyed接口并简单地将 a 传递给 KeyEnumMapping 构造函数,这会将枚举转换为其键:

public class KeyEnumMapping<K, E extends Enum<?>> {
    private Map<K, E> map = new HashMap<>();

    public KeyEnumMapping(Class<E> clazz, Function<E, K> keyExtractor) {
        E[] enumConstants = clazz.getEnumConstants();
        for (E e : enumConstants) {
            map.put(keyExtractor.apply(e), e);
        }
    }

    public E get(K key) {
        return map.get(key);
    }
}

public enum Example {
    A(1),
    B(3),
    C(7);

    private static final KeyEnumMapping<Integer, Example> MAPPING =
        new KeyEnumMapping<>(Example.class, Example::getValue);
    private Integer value;

    Example(Integer value) {
        this.value = value;
    }

    public Integer getValue() {
        return value;
    }

    public static Example getByValue(Integer value) {
        return MAPPING.get(value);
    }

    public static void main(String[] args) {
        System.out.println(Example.getByValue(3));
    }
}
Run Code Online (Sandbox Code Playgroud)