Java-对象数组排序

1.对对象数组排序:对象要提供一个compare方法比较对象的大小

2.代码

 1 package Test;
 2 
 3 public class TestObjectArray {
 4     
 5     public static void main(String[] args) {
 6         Date [] dates = new Date[5];
 7         dates[0] = new Date(2000,1,2);
 8         dates[1] = new Date(2001,2,3);
 9         dates[2] = new Date(1997,9,8);
10         dates[3] = new Date(2000,1,2);
11         dates[4] = new Date(1997,9,3);
12         
13         for(Date d : dates){
14             System.out.print(d+"	");
15         }
16         
17         System.out.println();
18         bubbleSort(dates);
19         
20         for(Date d : dates){
21             System.out.print(d+"	");
22         }
23         
24     }
25 
26     private static void bubbleSort(Date[] dates) {
27         Date tmp;
28         for(int i = dates.length - 1; i > 0; i--){
29             for(int j = 0; j < i; j++){
30                 if(dates[j].compare(dates[j+1]) > 0){
31                     tmp = dates[j];
32                     dates[j] = dates[j+1];
33                     dates[j+1] = tmp;
34                 }
35             }
36         }
37     }
38 
39     //选择排序
40     private static void selectSort(Date[] dates) {
41         int index;
42         Date temp;
43         for(int i = 0; i < dates.length; i++){
44             index = i;
45             for(int j = i; j < dates.length; j++){
46                 if(dates[index].compare(dates[j])>0){
47                     index = j;
48                 }
49             }
50             if(i!=index){
51                 temp = dates[i];
52                 dates[i] = dates[index];
53                 dates[index] = temp;
54             }
55         }
56     }
57 
58     
59 }
60 
61 class Date{
62     int year, month, day;
63 
64     public int getMonth() {
65         return month;
66     }
67 
68     public int getDay() {
69         return day;
70     }
71 
72     public int getYear() {
73         return year;
74     }
75 
76     public Date(int year, int month, int day) {
77         super();
78         this.year = year;
79         this.month = month;
80         this.day = day;
81     }
82     
83     @Override
84     public String toString() {
85         return year+"-"+month+"-"+day;
86     }
87     
88     public int compare(Date d){
89         return     this.getYear() > d.getYear() ? 1 : 
90                 this.getYear() < d.getYear() ? -1 :    //年份即不是大于,又不是小于,则一定是等于,等于则继续比较月份
91                 this.getMonth() > d.getMonth() ? 1 :
92                 this.getMonth() < d.getMonth() ? -1:
93                 this.getDay() > d.getDay() ?  1 :
94                 this.getDay() < d.getDay() ? -1 : 0;
95     }
96 }

3.运行结果:

原文地址:https://www.cnblogs.com/shamgod/p/4603891.html