I have written an enum class and I want to either get the attribute by type or get the type by attribute, but it seems impossible.
public enum AreaCode {
area1(7927),
area2(7928),
area3(7929);
private final int ac;
AreaCode(int ac) {
this.ac = ac;
}
int areaCode(){
return ac;
}
AreaCode area(int n) {
switch (n) {
case 7927: return AreaCode.area1;
case 7928: return AreaCode.area2;
case 7929: return AreaCode.area3;
}
}
}
The code above will not compile. How to make area(int n) work?
All you need to do is add a default case so the method always returns something or throws an exception:
or perhaps better