When should a class be Comparable and/or Comparator?

前端 未结 11 2620
醉话见心
醉话见心 2020-11-22 14:11

I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 14:20

    java.lang.Comparable

    1. To implement Comparable interface, class must implement a single method compareTo()

      int a.compareTo(b)

    2. You must modify the class whose instance you want to sort. So that only one sort sequence can be created per class.

    java.util.Comparator

    1. To implement Comparator interface, class must implement a single method compare()

      int compare (a,b)

    2. You build a class separate from class whose instance you want to sort. So that multiple sort sequence can be created per class.

提交回复
热议问题