在没有外部库的情况下以更紧凑的方式初始化哈希映射

时间:2015-09-26 13:53:35

标签: java

有没有办法让这段代码更紧凑?使用较少的线而不使用库?
我正在使用Java 7

public enum CustomType {
    TYPE_A,
    TYPE_B,
    TYPE_C,
}

private static final Map<Integer, CustomType> typeMappings = new HashMap<>();

static {
    typeMappings.put(513, CustomType.TYPE_A);
    typeMappings.put(520, CustomType.TYPE_A);
    typeMappings.put(528, CustomType.TYPE_A);
    typeMappings.put(530, CustomType.TYPE_A);
    typeMappings.put(532, CustomType.TYPE_A);
    typeMappings.put(501, CustomType.TYPE_B);
    typeMappings.put(519, CustomType.TYPE_B);
    typeMappings.put(529, CustomType.TYPE_B);
}

2 个答案:

答案 0 :(得分:5)

假设您可以完全控制映射和枚举类,那么解决此问题的更传统的方法是将映射嵌入到枚举中。

public enum CustomType {
    TYPE_A(513, 520, 528, 530, 532),
    TYPE_B(501, 519, 529),
    TYPE_C();

    private static final Map<Integer, CustomType> typeMappings = new HashMap<>();

    static {
        for (CustomType ct : values()) {
            for (int v : ct.mapto) {
                typeMappings.put(v, ct);
            }
        }
    }

    private final int mapto[];
    CustomType(int ... mapto) {
        this.mapto = mapto;
    }
}

答案 1 :(得分:1)

有一种方法可以使它更紧凑:

Map<Integer, CustomType> typeMappings2 = new HashMap<Integer, CustomType>() {{
    put(513, CustomType.TYPE_A);
    put(520, CustomType.TYPE_A);
    put(528, CustomType.TYPE_A);
    put(530, CustomType.TYPE_A);
    put(532, CustomType.TYPE_A);
    put(501, CustomType.TYPE_B);
    put(519, CustomType.TYPE_B);
    put(529, CustomType.TYPE_B);
}};

......但从美学角度看它也不是很漂亮。