Comparator vs Comparable
- Comparable interface can be used to provide single way of sorting and Comparator interface is used to provide different ways of
sorting.
- For using Comparable, Class needs to implement it and for using Comparator we don’t need to make any change in the class.
- Comparable interface is in
java.lang
package and Comparator interface is present injava.util
package. - If sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.
- We don’t need to make any code changes at client side for using Comparable,
Arrays.sort()
orCollection.sort()
methods automatically uses thecompareTo()
method of the class. For Comparator, client needs to provide the Comparator class to use in compare() method. - We can sort the list elements of Comparable type by Collections.sort(List) method and we can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.
*************************************************
API Testing Interview Question Set:
https://automationreinvented.blogspot.com/search/label/Rest-API
Kubernetes Interview Question Set
https://automationreinvented.blogspot.com/search/label/Kubernetes
Docker Interview Question Set
https://automationreinvented.blogspot.com/2020/02/top-18-docker-commands-for-aytomation.html
Linux Interview question Set
https://automationreinvented.blogspot.com/search/label/Linux
Automation Testing/SDET Framework Design
https://automationreinvented.blogspot.com/search/label/FrameworkDesign
Java Related Interview Question Set
https://automationreinvented.blogspot.com/search/label/Java
GIT Interview Question Set:
https://automationreinvented.blogspot.com/search/label/GIT
Coding Interview Question Set:
https://automationreinvented.blogspot.com/search/label/Coding%20Questions