當前位置:成語大全網 - 書法字典 - 如何對列表集進行逆序排序

如何對列表集進行逆序排序

【size = large】【color = red】要對列表進行排序,您需要為列表中安裝的這種類型的類實現壹個排序接口。

例如:

以下示例用於列表

Java代碼

公共類列表排序{

/**

* main()

* 2010-4-2,下午09:25:57

*/

公共靜態void main(String【】args ){

// TODO自動生成的方法存根

列表& lt我的對象& gtlists = new ArrayList & lt我的對象& gt();

MyObject obj1 =新的my object(“d“);

MyObject obj2 =新的my object(“a“);

lists . add(obj 1);

lists . add(obj 2);

Collections.sort(列表);

for(我的對象我的對象:列表){

system . out . println(my object . get content());

}

}

}

MyObject類實現了類似的& lt我的對象& gt{

私有字符串內容;

公共my object(String _ content ){

this.content = _ content

}

公共字符串get content(){

返回內容;

}

公共void setContent(字符串內容){

this.content =內容;

}

公共int compare to(my object對象){

// TODO自動生成的方法存根

if(null = = obj)返回1;

否則{

返回this . content . compare to(obj . content);

}

}

}

以下是Collections.sort方法。

Java代碼

公共靜態& ltt擴展可比& lt?超級T & gt& gtvoid排序(List & ltT & gt列表){

object【】a = list . to array();

arrays . sort(a)

列表叠代器& ltT & gtI = list . list iterator();

for(int j = 0;j & lta .長度;j++) {

I。next();

I。set((T)a【j】);

}

}

事實上,我們的MyObject類的方法compareTo是在Arrays.sort()中調用的。...

看..

Java代碼

公共靜態空排序(對象【】a ){

Object【】aux =(Object【】a . clone();

merge sort(aux,a,0,a.length,0);

}

Java代碼

私有靜態void merge sort(Object【】src,

對象【】目標,

int low,

int high,

int off ){

int length =高-低;

//對最小數組進行插入排序

if(長度& lt插入排序閾值){

for(int I =低;我& lt高;i++)

for(int j = I;j & gt低& amp& amp

((可比的)目的地【j-1】)。compare to(dest【j】)& gt;0;j -)

swap(dest,j,j-1);

返回;

}

//將dest的壹半遞歸排序到src中

int destLow =低電平;

int destHigh =高;

低+=關;

高+=關;

int mid =(低+高)& gt& gt1;

merge sort(dest、src、low、mid、-off);

merge sort(dest、src、mid、high、-off);

//如果列表已經排序,只需從src復制到dest。這是壹個

//優化可以更快地對接近有序的列表進行排序。

if(((可比)src【mid-1】)。compare to(src【mid】)& lt;= 0) {

system . array copy(src,low,dest,destLow,length);

返回;

}

//將排序後的兩半(現在在src中)合並到dest

for(int I = dest low,p = low,q = mid我& ltdestHighi++) {

if(q & gt;= high | | p & lt中期和中期。& amp((可比)src【p】)。compare to(src【q】)& lt;=0)

dest【I】= src【p++】;

其他

dest【I】= src【q++】;

}

}

【/color】【/size】

當然,這是實現排序的壹種方式。另壹種方法是實現比較器,實現這個接口,然後使用

collections . sort(List List,Comparator c);此方法用於排序。..