Concept

How can anonymous classes define custom Java comparators?

ComputerScienceOne / Comparators

"A Comparator can be created as an anonymous class, allowing a class to be defined and instantiated inline without declaring a named class or placing it in a separate .java source file. For example, an ascending Integer comparator can implement compare(Integer a, Integer b) by returning a.compareTo(b). A descending comparator can reverse the arguments and return b.compareTo(a). Anonymous classes are useful for ad-hoc or single-purpose classes because multiple instances of a Comparator generally are not needed when they would all have the same functionality. A comparator that directly compares Integer values with <, ==, and > may have problems: null values can cause a NullPointerException when unboxed, and == compares object references rather than the actual values. Using compareTo() avoids the == issue. Java also does not allow a comparator to freely reference and reuse an outside variable such as cmpInt unless that variable is final, because the variable could otherwise be reassigned outside the anonymous class."

Related Ideas

How can anonymous classes define custom Java comparators? | ComputerScienceOne | Bifalgorithm | Bifalgorithm