I have a Java enum that represents potential values for a given field, along with a unique identifier used to identify that value:
public enum MyEnum {
TYPEA("A"),
TYPEB("B")
private String code;
private MyEnum(String code){
this.code = code;
}
public String getCode(){
return code;
}
}
Id like to add a custom comparator:
public boolean equals(String code){
return getCode().equals(code);
}
This will allow me to compare my enums with strings.
Is there any pitfall that im missing? I cant see anything obviously wrong...
Well, two things:
MyEnum.A.equals("A")
is true, but "A".equals(MyEnum.A)
is false.I wouldn't do it - where you want to perform equality checks with the code, it's easy to do so... but it's clearer to be explicit about it.
After all, it's only the difference between:
if (value.equals("A"))
and
if (value.getCode().equals("A"))
and I'd argue that the latter is clearer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With