Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 }; 
like image 889
Joe Avatar asked Oct 25 '12 13:10

Joe


People also ask

Can we compare two enums?

You can compare two enum members of same or different type using the equals() method.

Can we call == to compare enums?

There are two ways for making comparison of enum members :equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Can you use == on enum Java?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.


1 Answers

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 } 
like image 134
Óscar López Avatar answered Sep 28 '22 01:09

Óscar López