Why should a Java class implement comparable?

后端 未结 10 650
忘掉有多难
忘掉有多难 2020-11-22 13:14

Why is Java Comparable used? Why would someone implement Comparable in a class? What is a real life example where you need to implement comparable

10条回答
  •  悲哀的现实
    2020-11-22 13:46

    Quoted from the javadoc;

    This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

    Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator.

    Edit: ..and made the important bit bold.

提交回复
热议问题