Java Enum compareTo()

www.lau‮oc.irutt‬m
Java Enum compareTo()

In Java, the compareTo() method is a member of the Comparable interface, which is implemented by the Enum class. The compareTo() method compares the current enum instance with another enum instance and returns a negative integer, zero, or a positive integer if the current instance is less than, equal to, or greater than the other instance, respectively.

Here's an example of how to use the compareTo() method with an enum in Java:

public enum Size {
    SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");

    private String abbreviation;

    private Size(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public String getAbbreviation() {
        return abbreviation;
    }

    public static void main(String[] args) {
        Size s1 = Size.SMALL;
        Size s2 = Size.LARGE;

        int result = s1.compareTo(s2);  // result is -2
        System.out.println(result);
    }
}

In this example, the Size enum has four constant values: SMALL, MEDIUM, LARGE, and EXTRA_LARGE. The compareTo() method is called on the SMALL constant and passed the LARGE constant as an argument. Since the SMALL constant is defined before the LARGE constant in the enum, the compareTo() method returns a negative integer.

You can use the compareTo() method to compare enum instances and determine their relative order. The compareTo() method is useful for sorting enum instances or for comparing them in other contexts.

Created Time:2017-11-03 15:57:10  Author:lautturi