Comparator

Leave a comment

December 18, 2016 by oneOokay

Array: 如 int[]: 用Arrays.sort()

List:如List: 用Collections.sort()

Arrays.sort(array, startIndex, endIndex, comparator):对array的一部分进行排序,startIndex:Inclusive; endIndex: exclusive.

new Comparator<T>(){
public int compare(T t1, T t2){
//如果t1的顺序应该在t2之前,那么传入正数; 如果t1的顺序应该在t2之后,那么传入负数.
//按T的某一个value从小到大排序的话,就直接t1.value - t2.value.
//若从大到小就倒过来:t2.value - t1.value
}}

Comparator可以用于PriorityQueue和Arrays.sort()/Collecions.sort()中:

PriorityQueue queue = new PriorityQueue<>(d.size(), comparator);
//注意comparator其实是一个private的object值,所以最后要有一个;
private Comparator comparator = new Comparator(){
    public int compare(T s1, T s2){
       return 0;
    }
 };
Integer.compare(a,b): return a - b;
如果a==b return 0
如果a>b: return 1
如果a按照:
String的长短排序 逆序排序:长的在前面.
String的lexicographically 顺序排序. 字母表处于前面的排前面.
Collections.sort(list, (a,b) -> a.length() != b.length() ? -Integer.compare(a.length(), b.length()) :  a.compareTo(b));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: