How does a comparable and comparator work internally?
Category:
technology and computing
programming languages
With Comparable, your class needs to implement the comparable interface and you need to override its compareTo method. So when you call the Collections. sort method on an object of your class, your implementation of the compareTo method is called INTERNALLY, and the objects are sorted accordingly.
Beside this, what is the difference between comparable and comparator?
Comparable v/s Comparator in Java Comparable interface is used to sort the objects with natural ordering. Comparator in Java is used to sort attributes of different objects. Comparable interface compares “this” reference with the object specified. Comparator provides compare() method, equals() method to sort elements.
- Java.
- To implements comparable interface, class must implement a single method compareTo()
- int a.
- A comparable object is comparing itself with another object.
- You must modify the class whose instance you want to sort.
- So that only one sort sequence can be created per class.
Similarly, you may ask, how do you use comparator and comparable?
Comparable vs Comparator
- Comparable interface can be used to provide single way of sorting whereas Comparator interface is used to provide different ways of sorting.
- For using Comparable, Class needs to implement it whereas for using Comparator we don't need to make any change in the class.
If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal. Finally, equals() compares the objects' fields.