Task 3 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 — what it unlocks

Lesson

Зачем оно нужно

Implementing one method makes your class work with the whole Java library. Collections.sort(list), Collections.max(list), Collections.min(list) — all of them call your compareTo and need nothing else.


Без Comparable библиотека отказывается

Collections.sort(listOfPlainObjects);
// error: no suitable method found for sort(ArrayList<Plain>)

This is not a runtime failure — the compiler refuses. Collections.sort demands that the element type be Comparable, and a class without it does not qualify.

So the contract is real: implement the interface and a lot of code you never wrote starts working with your objects.


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



Collections.sort orders your objects by...


Sorting a list of objects whose class is not Comparable gives...


Type exactly what this program prints.

import java.util.ArrayList;
import java.util.Collections;

class Item implements Comparable<Item> {
    private int price;

    public Item(int price) {
        this.price = price;
    }

    public int compareTo(Item other) {
        return price - other.price;
    }

    public String toString() {
        return "" + price;
    }
}

public class Main { public static void main(String[] a){
    ArrayList<Item> l = new ArrayList<Item>();
    l.add(new Item(30));
    l.add(new Item(10));
    l.add(new Item(20));
    Collections.sort(l);
    System.out.println(l);
}}

Which of these needs Comparable?


True or false?