I just found out that Java allows enums to implement an interface. What would be a good use case for that?
There is a case I often use. I have a IdUtil
class with static methods to work with objects implementing a very simple Identifiable
interface:
public interface Identifiable {
K getId();
}
public abstract class IdUtil {
public static & Identifiable, S> T get(Class type, S id) {
for (T t : type.getEnumConstants()) {
if (Util.equals(t.getId(), id)) {
return t;
}
}
return null;
}
public static & Identifiable, S extends Comparable super S>> List getLower(T en) {
List list = new ArrayList<>();
for (T t : en.getDeclaringClass().getEnumConstants()) {
if (t.getId().compareTo(en.getId()) < 0) {
list.add(t);
}
}
return list;
}
}
If I create an Identifiable
enum
:
public enum MyEnum implements Identifiable {
FIRST(1), SECOND(2);
private int id;
private MyEnum(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Then I can get it by its id
this way:
MyEnum e = IdUtil.get(MyEnum.class, 1);