Having the following definitions
public interface AnInt {
int value();
}
public enum FirstTwo implements AnInt {
ONE(() -> 1),
TWO(() -> 2);
}
Is there a way to correctly implement comparison to use standard equals:
class AnotherOne implements AnInt {
@Override
int value() {
return 1;
}
}
ONE.equals(new AnotherOne()); // -> true
CodePudding user response:
Given the equals()
of java.lang.Enum
(the parent of all enum
classes) is final, you can't do this.
And in general, considering objects of different classes, especially if there is no parent-child relation between those classes, equal is an accident waiting to happen (unless carefully designed). I recommend solving this in a different way (e.g. a custom comparison method, or wrapper classes that provide a facade for the equality check, a Comparator<AnInt>
implementation as companion to the AnInt
interface, etc).