When should a class be Comparable and/or Comparator?

前端 未结 11 2495
醉话见心
醉话见心 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:21

    here are few differences between Comparator and Comparable I found on web :

    1. If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

    2. Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

    3. If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method.

    4. Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

    site:How to use Comparator and Comparable in Java? With example

    Read more: How to use Comparator and Comparable in Java? With example

提交回复
热议问题