Java Enum compareTo() Method
Example
Compare the position of enum constants:
public class Main {
enum Level { LOW, MEDIUM, HIGH }
public static void main(String[] args) {
Level myVar = Level.MEDIUM;
System.out.println(Level.LOW.compareTo(myVar));
System.out.println(Level.MEDIUM.compareTo(myVar));
System.out.println(Level.HIGH.compareTo(myVar));
}
}
Definition and Usage
The compareTo() method compares two constants of the same enum by their position (the order in which they are written in the enum).
It returns a negative number if this constant comes before the other one, 0 if they are the same constant, and a positive number if it comes after. Java uses this order when it sorts enum constants, for example with Collections.sort().
Tip: Use ordinal() to get the position of a single constant.
Syntax
public final int compareTo(E o)
E refers to the enum type, for example Level.
Parameter Values
| Parameter | Description |
|---|---|
| o | Required. The constant to compare with. It must be from the same enum. |
Technical Details
| Returns: | An int: a negative number if this constant comes before o, 0 if they are the same constant, and a positive number if it comes after o. |
|---|
Related Pages
Java Enum Constructor Tutorial
❮ Enum Methods