有没有办法使此代码更紧凑?用更少的行而不使用库?
我正在使用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);
}
最佳答案
假设您对映射和枚举类都具有完全控制权,那么解决此问题的更传统的方法是将映射嵌入到枚举中。
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;
}
}