Comparator,comparable Interface Difference

Source: Internet
Author: User
Tags comparable sort

Recently, the function of doing an object sort needs to be sorted by different rules. Look at the arrays,collections, the Sort method,

Learn about the Comparator,comparable two interfaces, find the sort method that applies to yourself, and below put your own

Understand and collect what I think is the classic explanation as follows:

Comparable is a general-purpose interface that users can implement to perform their own specific comparisons, while comparator can be seen as an implementation of an algorithm that specifies the comparator when a container set collection needs to compare functions, which shows a design pattern Separates the algorithm from the data, just like the function object in the C + + STL.

The former should be more fixed and binding to a specific class, which is flexible and can be used for each class that needs to compare functions. It can be said that the former belongs to "static binding", while the latter can be "dynamic binding."

A class implements a Camparable interface that indicates that objects of this class can be compared to each other. If it is described in mathematical language, there is a whole sequence in the set of objects of this class. This way, the collection of class objects can be sorted by using the Sort method.

And the comparator has two functions:

1. If the class designers do not take into account the compare of the problem and do not implement the comparable interface, you can use comparator to implement the comparison algorithm to sort

2. Prepare for the use of different sorting criteria, such as ascending, descending, or other sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.