Java / Collections
Difference between Comparable and Comparator interface.
| Comparable. | Comparator. |
| Class whose objects to be sorted must implement this interface and to implement compareTo(Object) method. | Class whose objects to be sorted do not need to implement this interface. Instead a third class can implement this interface to sort and implement compare method. |
| Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects. | Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. |
| Collections.sort(List). Objects will be sorted on the basis of CompareTo method. | Collections.sort(List, Comparator). Objects will be sorted based on the Compare method in Comparator. |
| Comparable located in Java.lang package. | Comparator located in Java.util package. |
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
