Which is better comparable or comparator




















Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Skip to content. Change Language. Related Articles. Table of Contents. Save Article. Improve Article. Like Article. Attention reader! Previous Comparator Interface in Java with Examples. Recommended Articles. How to Fix java. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Lastly, the output is false, as variable p and s have different assigned values. Skip to content. What is Comparable in Java? What is Comparator in Java?

Comparable provides compareTo method to sort elements in Java whereas Comparator provides compare method to sort elements in Java. Comparable interface is present in java. Comparable provides single sorting sequence while Comparator provides multiple sorting sequences.

Comparator provides compare method to sort elements in Java. Comparator interface is present in java. The logic of sorting must be in the same class whose object you are going to sort.

The logic of sorting should be in separate class to write different sorting based on different attributes of objects. The class whose objects you want to sort must implement comparable interface. Class, whose objects you want to sort, do not need to implement a comparator interface. It provides single sorting sequences. It provides multiple sorting sequences. This method can sort the data according to the natural sorting order. This method sorts the data according to the customized sorting order.

It affects the original class. It is implemented to sort instances of third-party classes. Let's see an example of the Java Comparator interface where we are sorting the elements of a list using different comparators. This class provides comparison logic based on the name. In such case, we are using the compareTo method of String class, which internally provides the comparison logic.

JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services. Please mail your requirement at [email protected] Duration: 1 week to 2 week. Next Topic Properties in Java. Reinforcement Learning. R Programming. React Native. Python Design Patterns. Python Pillow. Python Turtle.

Verbal Ability. Interview Questions.



0コメント

  • 1000 / 1000