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 does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- How can comparator functions order Student structures?ComputerScienceOne · Comparator Functions
- What is a comparator function and how does it determine element order?ComputerScienceOne · Comparator Functions
- How does Java sort arrays and lists with comparators?ComputerScienceOne · Sorted Collections
- How do you implement a comparator for integers in C?ComputerScienceOne · Comparator Functions