Home > Blockchain >  Could java enum class implements "Comparable" interface?
Could java enum class implements "Comparable" interface?

Time:07-11

Seems that enum class already has a final compareTo function, which cannnot be overriden. But my requirement is to customize an enum class like this:

enum Operator {
    Add(' ', 1),
    Sub('-', 1),
    Mul('*', 2),
    Div('/', 2);

    private char op;
    private int priority;
    private Operator(char _op, int _priority) {
        op = _op;
        priority = _priority;
    }
}

Then I wish to have it implements Comparable interface to have the ability to compare among Add, Sub, Mul, etc. But seems I cannot use implements Comparable<Operator> as described above, javac gives compilation error:

Redundant superinterface Comparable<Operator> for the type Operator, already defined by Enum<Operator>Java(16777547)

So how to achieve my goal? Thanks.

CodePudding user response:

You can always declare Comparator.comparingInt(Operator::getPriority) and use it to compare your operators.

CodePudding user response:

Then I wish to have it implements Comparable interface to have the ability to compare among Add, Sub, Mul, etc

You can't do that.

Every enum implicitly implements Comparable because its parent java.lang.Enum has implemented this interface and method compareTo() is marked with final modifier, i.e. you can't override it.

Here is the quote from the Javadoc:

public final int compareTo(E o)

Compares this enum with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared.

The property priority is redundant, instead leverage the order your constants.

  • Related