"apple".compareTo("orange") returns:
Comparable, Comparator and Interfaces
The Comparable interface and compareTo (negative / zero / positive), sorting objects with Arrays.sort, the Fruit and Person examples, and the Comparator interface (compare, equals) for sorting by different attributes such as grade or name.
How to read this page
Every original slide is shown unchanged. Yellow marks on a slide point to a numbered note: hover or tap a mark to jump to its note, and hover a note to see its marks. Questions tagged Past exam appeared on a real paper; Prediction questions are likely angles, not confirmed. Pick an answer to each question: a wrong pick tells you why it is wrong, so you can try again.
All 20 slides
- 1 Slide 1
- 2 Slide 2
- 3 Objective
- 4 Java has many predefined interfaces that are used by
- 5 The Comparable Interface
- 6 The compareTo method should return
- 7 Class Person has name and age as instance variables Let class person implement interface Comparable
- 8 Fruit Example
- 9 Java doesn’t know how to compare two instances of the
- 10 The Arrays.sort method has been written with the
- 11 Slide 11
- 12 Lexicographic ordering is same as alphabetical
- 13 That is, if we have two strings str1 and str2 then
- 14 Fruit Code
- 15 The Comparator interface
- 16 The compare Method:
- 17 Example of using Comparator interface
- 18 We create an array of Students, three objects of type
- 19 Output
- 20 The equals Method:
The compareTo method should return
Exam angle
The Arrays.sort method has been written with the
Exam angle
Arrays.sort can sort an array of your own class even if it doesn’t implement Comparable (and no Comparator is given).
- It throws ClassCastException.
The Comparator interface
Notes
Comparator (java.util) defines compare(a, b) and equals; use it for orderings other than the natural one.
Example of using Comparator interface
Notes
Use Comparator to sort by different attributes: Arrays.sort(students, new GradeComparator()).
Memory trick Comparable = ONE built-in order inside the class. Comparator = MANY orders in separate classes.
Exam angle
To sort students sometimes by name and sometimes by grade, you should use: