jeudi 12 juillet 2018

Singleton of Java functional interface as enum

While looking at the source code of the Comparators class, I came across these lines of code.

class Comparators {

    //...

    enum NaturalOrderComparator implements Comparator<Comparable<Object>> {
        INSTANCE;

        @Override
        public int compare(Comparable<Object> c1, Comparable<Object> c2) {
            return c1.compareTo(c2);
        }

        @Override
        public Comparator<Comparable<Object>> reversed() {
            return Comparator.reverseOrder();
        }
    }

    //...

}

I think I understand what this does. It's a Singleton instance which implements the Comparator interface. It uses the "compareTo" of classes that implement the Comparable interface for natural ordering (please correct me if I am wrong in any of this).

What I do not understand however, why is it done using an enum. I really like enums for Singletons, don't get me wrong but in this case I personally think this would have been simpler:

public static final Comparator<Comparable<Object>> NATURAL_ORDER_COMPARATOR =
    new Comparator<Comparable<Object>>() {
        @Override
        public int compare(Comparable<Object> c1, Comparable<Object> c2) {
            return c1.compareTo(c2);
        }

        //...

    }

Are there any reasons to implement this using enums aside from personal preference?

Aucun commentaire:

Enregistrer un commentaire