Why should a Java class implement comparable?

后端 未结 10 607
忘掉有多难
忘掉有多难 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:30

    The fact that a class implements Comparable means that you can take two objects from that class and compare them. Some classes, like certain collections (sort function in a collection) that keep objects in order rely on them being comparable (in order to sort you need to know which object is the "biggest" and so forth).

提交回复
热议问题