Differences between comparable and comparator

Source: Internet
Author: User

I. Comparison

Comparable & comparator are used to compare and sort elements in a set, but comparable is an internal sort and comparator is an external sort.

Using comparator is a strategy design pattern. Instead of changing the object itself, a strategy object is used to change its behavior.

For example, if you want to sort Integers by absolute values, integer does not meet the requirements. You do not need to modify the integer class (you cannot actually do this) to change its sorting behavior, as long

Use an object that implements the comparator interface to control its sorting.

 

II. Introduction
1. java. util. Comparator

Intcompare(T o1, T o2) 

Booleanequals(Object obj) 

A comparison function, which imposesTotal OrderingOn some collection of objects. comparators can be passed to a sort

Method (suchCollections.sortOrArrays.sort) To allow precise control over the sort order. comparators can also be used

Control the order of certain data structures (suchsorted setsOrsorted maps), Or to provide an ordering for collections of Objects

That don't havenatural ordering.

public static <T> void sort(List<T> list,                            Comparator<? super T> c)

 

2. java. Lang. Comparable

    int compareTo(T o) 

Lists (and arrays) of objects that implement this interface can be sorted automaticallyCollections.sort(AndArrays.sort).

Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need

Specify a comparator.



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.