简体   繁体   中英

What is the best way to compare enum and non-enum objects in Java?

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

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 (eg 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM