You have a couple of straightforward options available to you. One is to use a Map<Integer, String>
and another is to to a linear search.
Using a map is probably much more efficient, but will take up more space. This is probably not an issue for a small number of enums.
public enum KDErrors {
KDR_280(280, "Blue"),
KDR_281(281, "Red"),
KDR_282(282, "Green"),
KDR_284(284, "Yellow"),
private static Map<Integer, String> codeMap = new HashMap<>();
private final int code;
private final String color;
private KDErrors(int code, String color) {
this.code = code;
this.color = color;
codeMap.put(code, color);
}
public static String getColorByCode(int colorCode) {
return codeMap(colorCode);
}
}
Doing a linear search prevents you from having to allocate additional structures, but it will be a little slower for the average case than a lookup in a HashMap
:
public enum KDErrors {
KDR_280(280, "Blue"),
KDR_281(281, "Red"),
KDR_282(282, "Green"),
KDR_284(284, "Yellow"),
private final int code;
private final String color;
private KDErrors(int code, String color) {
this.code = code;
this.color = color;
}
public static String getColorByCode(int colorCode) {
for(KDErrors err : KDErrors.values()) {
if(err.getCode() == colorCode)
return error.getColor();
}
return null;
}
}