氟塑料离心泵www.buybeng.com

jquery教程http://www.software8.co/wzjs/jquery/

用冒泡法对引用类型进行排序

 这篇博文涉及到的知识点:

              1、定义引用类型的数组

              2、为引用类型添加了一个比较的方法Compare

              3、重写了toString方法

              4、用到了冒泡排序

             源代码如下:

  1. public class TestDateSort  
  2. {  
  3.     public static void main(String args[])  
  4.     {  
  5.         Date[] d=new Date[5];  
  6.         d[0]=new Date(2006,5,4);  
  7.         d[1]=new Date(2006,7,4);  
  8.         d[2]=new Date(2008,5,4);  
  9.         d[3]=new Date(2004,5,9);  
  10.         d[4]=new Date(2004,5,4);  
  11.           
  12.         bubbleSort(d);  
  13.           
  14.         for(int i=0;i<=d.length-1;i++)  
  15.         {  
  16.             System.out.println(d[i]);  
  17.         }  
  18.     }  
  19.       
  20.     //用冒泡排序法,进行排序  
  21.     public static void bubbleSort(Date[] d)  
  22.     {  
  23.         for(int i=d.length-1;i>=1;i--)  
  24.         {  
  25.             for(int j=0;j<i;j++)  
  26.             {  
  27.                 if(d[j].Compare(d[j+1])>0)  
  28.                 {  
  29.                     Date temp;  
  30.                     temp=d[j];d[j]=d[j+1];d[j+1]=temp;  
  31.                 }  
  32.             }  
  33.         }  
  34.     }  
  35. }  
  36.   
  37. class Date  
  38. {  
  39.     int year,month,day;  
  40.     Date(int y,int m,int d)  
  41.     {  
  42.         year=y;month=m;day=d;  
  43.     }  
  44.       
  45.     //定义一个比较的方法  
  46.     public int Compare(Date date)  
  47.     {  
  48.         return year>date.year?1  
  49.                 :year<date.year?-1  
  50.                 :month>date.month?1  
  51.                 :month<date.month?-1  
  52.                 :day>date.day?1  
  53.                 :day<date.day?-1:0;  
  54.     }  
  55.     //重写toString方法  
  56.     public String toString()  
  57.     {  
  58.         return "year-month-day:"+year+"-"+month+"-"+day;  
  59.     }  
  60. }  


运行效果如图所示:

 

 

 

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

posted on 2012-10-05 10:15 你爸是李刚 阅读(868) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2012年10月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿

随笔档案

文章档案

技术网站

行业网站

搜索

最新评论

阅读排行榜

评论排行榜

站长网 氟塑料离心泵 注塑机 液晶广告机