Comparator interface and comparator interface in Java

Source: Internet
Author: User
Tags comparable

Comparator is located under Package Java.util, the comparator, which is defined in the collection outside the sorting.
Comparable is located under Package Java.lang, which represents the comparison of the current object, and is the implementation of sorting within the collection.

Comparable represents an object that supports ordering internally (such as the String class, the integer class, the internal implementation of the comparable interface) Collections.sort (list<t>), T must implement the comparable interface.

Comparable simply implement the CompareTo () function to

public int CompareTo (Object arg0) {//TODO auto-generated method Stubreturn 0;}



Comparator represents a strategy pattern (strategy design pattern), which does not change the object itself, but uses a policy object (strategy object) to change its behavior. For example, sort the list<integer> by absolute value. Collections.sort (List<t>,comparator).

Collections.sort (list, new comparator<node2> () {public int compare (Node2 O1, Node2 O2) {return 0;} equals is used to determine whether two comparisons are equal, because the Object class has the default equals, so you can not write Equalspublic Boolean equals (Object O) {return false;}});

so you can see that the comparator interface is more flexible!

Comparator interface and comparator interface in Java

Related Article

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.