Equal overload in listing - any pitfalls?

I have a Java enumeration representing potential values ​​for a given field, as well as a unique identifier used to identify this value:

public enum MyEnum { TYPEA("A"), TYPEB("B") private String code; private MyEnum(String code){ this.code = code; } public String getCode(){ return code; } } 

I like to add a custom comparator:

 public boolean equals(String code){ return getCode().equals(code); } 

This will allow me to compare my listings with strings.

Is there some kind of error that I have lost? I do not see anything clearly wrong ...

+4
source share
2 answers

Well, two things:

  • You do not redefine - you are overloaded and confused.
  • Your equality is not symmetrical - MyEnum.A.equals("A") true, but "A".equals(MyEnum.A) is false.

I would not do this - where you want to perform equality checks with the code, this is easy to do ... but it will be clearer explicit.

In the end, this is just the difference between:

 if (value.equals("A")) 

and

 if (value.getCode().equals("A")) 

and I would say the latter is clearer.

+14
source

The trap is quite simple: you did not redefine equals(Object) , you introduced another equals(String) method. This method will not be used by any calls to the equals infrastructure for your object, since dynamic dispatch applies to the run-time type of only the object in which the method is called, and the static type of all method arguments is used to allow the signature of the method at compile time.

If you β€œfix” it to equals(Object) , but save the logic, then you broke the equals contract because you do not satisfy the symmetry property: if another string is compared with your object via String.equals(yourObject) it will return false, and you will you cannot influence it. This is a limitation of using the Java one-time send mechanism to determine the equality relationship.

Fortunately, the enumerations already prevent you from doing this with hardcoding equals and hashCode and make them final.

+6
source

Source: https://habr.com/ru/post/1469524/


All Articles