Concept
What is the difference between Comparable and Comparator in Java?
ComputerScienceOne / Comparators
"Each of Java’s standard types implements something similar called the Comparable interface, which specifies a compareTo() method with the same basic contract. Strings use lexicographic ordering, while numeric types such as Integer and Double use compareTo() methods that order elements in ascending order. Java refers to these built-in orderings as natural orderings. For user-defined classes, the ordering must be specified. A class can implement Comparable<T>, but doing so locks the class into one natural ordering. A Comparator is more flexible because different orderings can be defined, including descending order, even for wrapper classes that already have a natural ordering."
Related Ideas
- How can Comparator order Student objects by different fields?ComputerScienceOne · Comparators
- How does Java perform binary searches on arrays and lists?ComputerScienceOne · Sorted Collections
- How can a Comparator sort Student objects by GPA?ComputerScienceOne · Searching
- How does Java sort arrays and lists with comparators?ComputerScienceOne · Sorted Collections
- How can method references and Comparator methods make ordering more concise?ComputerScienceOne · Java 8: Lambda Expressions
- What are sorted collections in the Java Collections framework?ComputerScienceOne · Sorted Collections
- How can lambda expressions build a multi-field Comparator?ComputerScienceOne · Java 8: Lambda Expressions
- How should a Comparator order elements in a SortedSet?ComputerScienceOne · Handling javanull values