Explanation of generic > in collection.sort/ comparable code?

前端 未结 2 716
抹茶落季
抹茶落季 2020-11-28 23:52

I use comparable interface all the time to provided natural ordering for my class through collection.sort.

Basically if I have a person class, I will get it to imple

2条回答
  •  执笔经年
    2020-11-29 00:39

    Actually, it means that T can implement Comparable, not just Comparable.

    For example, it means that a Student class can implement Comparable, where Student is a subclass of Person:

    public class Person {}
    
    public class Student extends Person implements Comparable {
        @Override public int compareTo(Person that) {
            // ...
        }
    }
    

    In this case, a List can be sorted by Collections.sort() but only based on Person's properties, because you pass the Student instance into compareTo() as a Person (unless you downcast it, of course).

    In practice however, you'll never see a Student class implement Comparable. That's because Person will probably have implemented Comparable, and Student inherits it implementation. The end result is the same however: you can pass a List to Collections.sort() and have it sorted on Person's properties.

    The difference between Comparable and Comparable is more obvious in the overloaded version of Collections.sort() that takes a Comparator:

    class ByAgeAscending implements Comparator {
        @Override public int compare(Person a, Person b) {
            return a.getAge() < b.getAge();
        }
    }
    
    List students = getSomeStudents();
    Collections.sort(students, new ByAgeAscending());
    

提交回复
热议问题