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.