本來(lái)一直在CSDN上寫(xiě)口渔,然后今天不知道為什么CSDN上發(fā)表不了文章了御铃,正好我聽(tīng)朋友的介紹來(lái)到這里,希望和大家一起討論問(wèn)題歧焦。其實(shí)說(shuō)白了我寫(xiě)博客大多數(shù)是為了記錄自己的成長(zhǎng)過(guò)程移斩,順便整理自己學(xué)習(xí)情況。再者利索能力的和大家一起交流經(jīng)驗(yàn)绢馍,話不多說(shuō)向瓷,正文開(kāi)始。
本人快要找工作了舰涌,看到日益嚴(yán)峻的就業(yè)情況猖任,感到壓力很大,最近在復(fù)習(xí)算法的部分瓷耙,偶然想不知道java中的排序是怎么樣實(shí)現(xiàn)的朱躺,然后就有了一番源碼中的遨游。分兩節(jié)分享給大家搁痛。
概述
首先我們?cè)偈褂玫臅r(shí)候都是這樣的:
Collections.sort(List list , Comparator<? super T> c)
首先我們看一下官方文檔的描述
Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The specified list must be modifiable, but need not be resizable.
這里意識(shí)流翻譯一下:
你要排序就用我的sort()方法就行长搀,但是要保證list中的內(nèi)容是可比較的或者有比較器的存在。什么叫可比較的呢落追?那就是實(shí)現(xiàn)Comparable接口啦~于是引出第一種排序方式
實(shí)現(xiàn)Comparable接口
有人可能要問(wèn)了盈滴,為什么我在使用List<Integer>的時(shí)候沒(méi)有這種覺(jué)悟呢?——是因?yàn)閖ava內(nèi)包括Integer在內(nèi)的很多類都實(shí)現(xiàn)了這個(gè)接口轿钠。博主在自己的專業(yè)版IDEA中使用ctrl+H可以看到具體有哪些實(shí)現(xiàn)類
但是這里也有一些問(wèn)題,在使用過(guò)程中病苗,我們有很多需求是按照一定的序列量自定義對(duì)象排序疗垛,那這個(gè)問(wèn)題怎么實(shí)現(xiàn)呢?這里只要實(shí)現(xiàn)Comparable接口就行了啊~話不多說(shuō)上代碼:
class PCB implements Comparable<PCB>{
private int ID;
private int Priority;
private int CPUTime;
private int AllTime;
private int StartBlock;
private int BlockTime;
private String State;
......
Getter&Setter&Constructor
......
@Override public int compareTo(PCB o) {
// return (Priority > o.Priority) ? 1 : (Priority == o.Priority) ? 0 : -1;
return Priority - o.Priority;
}
注釋部分和下面一行是一個(gè)意思硫朦,為什么呢贷腕?我們來(lái)看一眼API:
a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
這就是真相。。但是泽裳,也要遵循基本法不是瞒斩?
1. sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.
2.(x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
3. x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z))
這里舉個(gè)例子:
return (Priority > o.Priority) ? 1 : -1;
這一點(diǎn)就違反了第一條規(guī)定.
在實(shí)際開(kāi)發(fā)中我們可能會(huì)遇見(jiàn)這樣的情況,我對(duì)于同一個(gè)對(duì)象有不同的排序需求涮总,按照之前的例子胸囱,如果我有時(shí)候要按照ID排序怎么辦?這時(shí)候比較器 Comparator登場(chǎng)
使用比較器
比較器的出現(xiàn)解決了很好的滿足了我們的需求瀑梗。怎么用呢烹笔?話不多說(shuō)看代碼:
Collections.sort(list, new Comparator<PCB>() {
@Override public int compare(PCB o1, PCB o2) {
return o2.getID() - o1.getID();;
}});
這里我們可以看到,通過(guò)重寫(xiě)compare()方法來(lái)實(shí)現(xiàn)抛丽,至于描述和遵循的基本法谤职,和上面的compareTo()方法是一致的。
好了亿鲜,現(xiàn)在來(lái)sort中兩個(gè)參數(shù)大家應(yīng)該都了解了吧有什么疑問(wèn)或者本文有什么問(wèn)題歡迎再留言區(qū)和我互動(dòng)啊