Java Enum compareTo
In this chapter you will learn:
- How to use Java Enum compareTo
- Syntax for Java Enum compareTo
- Return value from Java Enum compareTo
- Example - compare the ordinal value of two constants of enum
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 .ja va 2 s . c o m*/
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.
Next chapter...
What you will learn in the next chapter:
- How to use Java Enum equals
- Example - Compare for equality an enumeration constant with any other object