有没有办法让这个代码更紧凑?没有使用库的线路更少?
我使用的是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);
}
Run Code Online (Sandbox Code Playgroud)
假设您可以完全控制映射和枚举类,那么解决此问题的更传统的方法是将映射嵌入到枚举中.
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;
}
}
Run Code Online (Sandbox Code Playgroud)