Java Enum compareTo
Description
You can compare the ordinal value of two constants of the same enumeration by using the compareTo() method.
Syntax
final int compareTo(enum-type e)
enum-type
is the type of the enumeration,
and e is the constant being compared to the invoking constant.
Return
If the two ordinal values are the same, then zero is returned. If the invoking constant has an ordinal value greater than e's, then a positive value is returned.
Example
Compare the ordinal value of two constants of enum
enum Direction {/*from w w w . j av a2 s . c om*/
East, South, West, North
}
public class Main {
public static void main(String args[]) {
Direction ap = Direction.West;
Direction ap2 = Direction.South;
Direction ap3 = Direction.West;
if (ap.compareTo(ap2) < 0){
System.out.println(ap + " comes before " + ap2);
}
if (ap.compareTo(ap2) > 0){
System.out.println(ap2 + " comes before " + ap);
}
if (ap.compareTo(ap3) == 0){
System.out.println(ap + " equals " + ap3);
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »