- Comparable imposes a natural ordering; it has one method: compareTo.
- a.compareTo(b) returns NEGATIVE if a comes before b, ZERO if equal, POSITIVE if a comes after b.
🎯 How this can come up · 1 question
"apple".compareTo("orange") returns:
Correct: A negative number.
- Person implements Comparable<Person> and compares by age: return this.age - other.age;
- Arrays.sort calls compareTo on the objects, so they must implement Comparable.
🎯 How this can come up · 1 question
Arrays.sort can sort an array of your own class even if it doesn’t implement Comparable (and no Comparator is given).
False. It throws ClassCastException.
- Comparator (java.util) defines compare(a, b) and equals; use it for orderings other than the natural one.
- compare(obj1, obj2): 0 if equal, positive if obj1 > obj2, negative otherwise.
- Use Comparator to sort by different attributes: Arrays.sort(students, new GradeComparator()).
🎯 How this can come up · 1 question
To sort students sometimes by name and sometimes by grade, you should use:
Correct: Separate Comparator classes.
No slides match this filter.