自定義物件陣列的排序

2021-06-04 19:24:03 字數 1219 閱讀 9880

定義乙個

student

類,擁有兩個屬性,即姓名(

string name

)和年齡(

int age

),如果現在我宣告了乙個

student

類的物件陣列,那麼,如何利用

arrays.sort

()方法對這個自定義物件陣列加以排序。

其實,很簡單,只需要做到以下3點即可:

首先,讓需要進行排序的自定義類,如student,去實現comparable 介面;

其次,重寫comparable介面唯一的方法:intcompareto(object o) ;

最後,呼叫arrays.sort()方法對自定義物件陣列加以排序。

這裡,我寫了乙個簡單的程式加以說明,如下:

public class test ;

system.out.println("----------before sorted---------");

for (student e : mystudent)

system.out.println(e);

system.out.println("/n/n----------after sorted---------");

arrays.sort(mystudent);

for (student e : mystudent)

system.out.println(e);

}}

class student implements comparable 

public string tostring()

public int compareto(object o)

return result;

} }----------before sorted---------

name:zhangsan age:22

name:lisi age:24

name:wangwu age:22

name:zhaoliu age:23

----------after sorted---------

name:wangwu age:22

name:zhangsan age:22

name:zhaoliu age:23

name:lisi age:24

物件型別陣列 自定義排序

我們可以對任何物件型別的陣列排序,比如,物件person有名字和年齡屬性,我們希望根據年齡排序,那麼我們可以這麼寫 const friends function compareperson property if a property b property return 0 console.log ...

物件陣列。自定義物件

定義學生類屬性 自定義方法 顯示學生資訊方法年齡增加方法測試類 建立用於儲存學生的陣列,長度為5,建立5個學生物件,將物件儲存到陣列中遍歷陣列中的學生物件,分別呼叫年齡增加方法,將學生年齡增加2遍歷陣列中的學生物件,分別呼叫顯示資訊的方法,檢視所有學生資訊查詢年齡大於20的學生資訊 針對這個作業。寫...

JavaScript自定義陣列排序

array中有自帶的排序功能,這個使用起來比較方便,我們有一點必須清楚,就是排序的依據,如果sort不傳入引數的話,那就是按照字元編碼 unicode編碼 的順序排序。var a 3 2 1 console.log a 0 charcodeat 0 51 console.log a 1 charco...