巧用java的sort排序

   在進行程序編寫時,時常會遇到一些排序的問題,往往程序性能的怎麼樣,往往就在這些地方可以體現出來,因爲有時候,程序會花大量的時間來運行這些排序上的算法,而在JAVA裏面,已經有了一個sort算法,它能夠減少你大量的時間來進行排序,而且用起來比較簡單,只需要定義好排序的規則即可。

    一般使用方法是:java.util.Collections.sort(c lass something);  當然,如果只是這樣是不行的,必須還要做一個事情,就是給這個class類定義好Comparable接口,否則將會出現錯誤,查看Integer 的compareTo()方法: public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));

這裏要了解的重點是,當return 的值大於0時,this的值將會排到anotherInteger值的後面,反之return的值小於0時,this將排在anotherInteger前面。

我們再分析一個例子:

@Override
public int compareTo(FileInfo another) {
// TODO Auto-generated method stub
if (another.directory) {
if (!directory)
return 1;
return this.name.compareTo(another.name);
}
if (directory)
return -1;
return this.name.compareTo(another.name);
}


}

當another是文件夾時,且當時不爲文件夾時,this排在 another的後面,當this也爲文件夾時,再用名字作比較(這裏是根據字符串規則來作比較),

當another不爲文件夾時,且this爲文件夾時,返回-1 ,表示 this排在another的前面。


這裏的compareTo的作用,就是在制定一個作比較的規則,之後的事,則由java來進行排序,在性能上要比一般的算法要好得多。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章