Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

8.2 Comparable — the ordering contract

Lesson

Интерфейс, который вы уже встречали

Comparable is the interface Java itself defines, and it has exactly one method: compareTo. Implementing it means promising «objects of my class know how to compare themselves to each other».

You have used it already without noticing: String and Integer implement Comparable — that is why "apple".compareTo("banana") works.


Как реализовать

class Student implements Comparable<Student> {
    private int score;

    public int compareTo(Student other) {
        return score - other.score;   // negative / 0 / positive
    }
}

The contract is about the sign, not the number: negative means «I come first», 0 means equal, positive means «the other comes first». Subtracting is the shortest way for numbers. (For very large values the subtraction can overflow; Integer.compare(a, b) is the safe version.)

Notice: your class decides its own natural order. For students by score, for books by year, for cards by rank.


▶ Try it: run this, then change something and run it again.



How many methods does Comparable require?


compareTo must return a negative number when...


Type exactly what this program prints.

class Box implements Comparable<Box> {
    private int size;

    public Box(int size) {
        this.size = size;
    }

    public int compareTo(Box other) {
        return size - other.size;
    }
}

public class Main { public static void main(String[] a){
    Box small = new Box(2);
    Box big = new Box(9);
    System.out.println(small.compareTo(big));
    System.out.println(big.compareTo(small) > 0);
}}

Why do String and Integer already have compareTo?


True or false?