用冒泡法對(duì)引用類(lèi)型進(jìn)行排序
這篇博文涉及到的知識(shí)點(diǎn):
1、定義引用類(lèi)型的數(shù)組
2、為引用類(lèi)型添加了一個(gè)比較的方法Compare
3、重寫(xiě)了toString方法
4、用到了冒泡排序
源代碼如下:
[java] view plaincopy
- public class TestDateSort
- {
- public static void main(String args[])
- {
- Date[] d=new Date[5];
- d[0]=new Date(2006,5,4);
- d[1]=new Date(2006,7,4);
- d[2]=new Date(2008,5,4);
- d[3]=new Date(2004,5,9);
- d[4]=new Date(2004,5,4);
- bubbleSort(d);
- for(int i=0;i<=d.length-1;i++)
- {
- System.out.println(d[i]);
- }
- }
- //用冒泡排序法,進(jìn)行排序
- public static void bubbleSort(Date[] d)
- {
- for(int i=d.length-1;i>=1;i--)
- {
- for(int j=0;j<i;j++)
- {
- if(d[j].Compare(d[j+1])>0)
- {
- Date temp;
- temp=d[j];d[j]=d[j+1];d[j+1]=temp;
- }
- }
- }
- }
- }
- class Date
- {
- int year,month,day;
- Date(int y,int m,int d)
- {
- year=y;month=m;day=d;
- }
- //定義一個(gè)比較的方法
- public int Compare(Date date)
- {
- return year>date.year?1
- :year<date.year?-1
- :month>date.month?1
- :month<date.month?-1
- :day>date.day?1
- :day<date.day?-1:0;
- }
- //重寫(xiě)toString方法
- public String toString()
- {
- return "year-month-day:"+year+"-"+month+"-"+day;
- }
- }
運(yùn)行效果如圖所示:
代碼中的那個(gè)compare方法寫(xiě)的挺另類(lèi)的,不過(guò)我想大家應(yīng)該可以看懂!
posted on 2012-10-05 10:15 你爸是李剛 閱讀(882) 評(píng)論(0) 編輯 收藏