用冒泡法对引用类型进行排序
这篇博文涉及到的知识点:
1、定义引用类型的数组
2、为引用类型添加了一个比较的方法Compare
3、重写了toString方法
4、用到了冒泡排序
源代码如下:
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]);}}//用冒泡排序法,进行排序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;}//定义一个比较的方法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;}//重写toString方法public String toString(){return "year-month-day:"+year+"-"+month+"-"+day;}}
运行效果如图所示:

代码中的那个compare方法写的挺另类的,不过我想大家应该可以看懂!