数组-对引用类型的排序-冒泡法

来源:互联网 发布:linux mmap shm 编辑:程序博客网 时间:2024/06/04 01:10

对数组的引用类型(类的对象)进行排序

1.注意要重写toString方法









public class DateSort {public static void main(String[] args){Date[] days = new Date[5];days[0] = new Date(2016, 5, 4);days[1] = new Date(2016, 7, 4);days[2] = new Date(2018, 5, 4);days[3] = new Date(2010, 5, 9);days[4] = new Date(2010, 5, 4);Date d = new Date(2016, 7, 4);bubbleSort(days);//调用排序的方法for(int i=0; i<days.length; i++){//打印排序后的顺序System.out.println(days[i]);}}public static void bubbleSort(Date[] a){int len = a.length;for(int i = len-1; i >= 1; i--){//冒泡法排序for(int j = 0; j<= i-1; j++){if( a[j].compare(a[j+1]) >0) {Date temp = a[j];a[j] = a[j+1];a[j+1] = temp;}}}}}class Date{int year, month, day;Date(int x, int y, int z){year = x; month = y; day = z;}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;}public String toString(){//重写toString方法,否则返回的是days[]的哈希码return "Year:Month:Day--"+ year + "-" + month + "-" + day;}}




0 0
原创粉丝点击