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 };
You can compare two enum members of same or different type using the equals() method.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With