How can't we compare two enum values with '<'?

26,129

Solution 1

You can do this:

PinSize.BIGGEST.ordinal() > PinSize.BIG.ordinal()  // evaluates to `true`

Of course, assuming that BIGGEST was declared after BIG in the enumeration. The ordinal value in an enumeration is implicitly tied to the declaration order, by default the first value is assigned value 0, the second value 1 and so on.

So if yo declared the enumeration like this, things will work:

public enum PinSize {
    SMALLEST,  // ordinal value: 0
    SMALL,     // ordinal value: 1
    NORMAL,    // ordinal value: 2
    BIG,       // ordinal value: 3
    BIGGER,    // ordinal value: 4
    BIGGEST;   // ordinal value: 5
}

Solution 2

Implementing Comparable doesn't mean that you can use < or >. You can only use those with numeric values.

Implementing Comparable means that there's a compareTo() method. Try this:

System.out.println(PinSize.BIG.compareTo(PinSize.BIGGER));

The compareTo() method will return an int that is smaller than, equal to, or bigger than 0, depending on which value is "bigger". In the case of enum values, the "size" depends on the order of the enum value definitions.

Solution 3

The answers provided explain the problem well, but I would like to add my insights, because I feel that they don't answer question "why can't compare with < or >"?. The problem comes down to comparing references. PinSize.BIGGEST and PinSize.BIGGERER are reference variables. The same as the below:

String s;
int[] array;
MyObject myObject;

They represent addresses in memory. What is more, enums are singletons so there is always one object of the specified kind. Because of that the below line is allowed and returns true.

System.out.println(PinSize.BIG == PinSize.BIG); //true

Trying to check if one address in memory is greater or smaller than the other address in memory is impossible. Implementing Comparable interface and compareTo() method gives a chance to provide your own custom way of comparing objects not addresses in memory.

System.out.println(PinSize.BIG > PinSize.BIGGERER); // not possible
Share:
26,129
Joe
Author by

Joe

Updated on July 11, 2022

Comments

  • Joe
    Joe almost 2 years

    If enum implements Comparable so why can't compare with < or >?

    public class Dream    
    {
        public static void main(String... args)
        {
            System.out.println(PinSize.BIG == PinSize.BIGGER); //false
            System.out.println(PinSize.BIG == PinSize.BIG); //true
            System.out.println(PinSize.BIG.equals(PinSize.BIGGER));//false
            System.out.println(PinSize.BIG > PinSize.BIGGERER);// compilation error
            //can't be compared
            System.out.println(PinSize.BIG.toString().equals(PinSize.BIGGER));// #4
            PinSize b = PinSize.BIG ;
            System.out.println( b instanceof Comparable);// true
        }  
    }
    enum PinSize { BIG, BIGGER, BIGGERER };