Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading equals method in enum - any pitfalls?

Tags:

java

enums

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...

like image 662
PaulJWilliams Avatar asked Nov 30 '22 04:11

PaulJWilliams


1 Answers

Well, two things:

  • You're not overriding - you're overloading, and in a confusing way
  • Your equality is not symmetric - 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.

like image 54
Jon Skeet Avatar answered Dec 02 '22 18:12

Jon Skeet