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 a Comparator sort Student objects by GPA?ComputerScienceOne · Searching
- What are sorted collections in the Java Collections framework?ComputerScienceOne · Sorted Collections
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- How can a Java Comparator handle null values?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- How do you compare strings in Java?ComputerScienceOne · Comparisons
- How can lambda expressions build a multi-field Comparator?ComputerScienceOne · Java 8: Lambda Expressions
- How can method references and Comparator methods make ordering more concise?ComputerScienceOne · Java 8: Lambda Expressions
- How does Java sort arrays and lists with comparators?ComputerScienceOne · Sorted Collections