大伙看看 本来我是要排序的 但是 打印出来的结果却没有
但是用上面的 注释掉的 for 循环却能正确排序
我想很多人都认为 java 有引用调用
但是 java 只用值调用 没有引用调用!
我想很多人都碰到过这样的问题 我觉得 很人会在这个地方犯错
希望大家注意- package javatext;
- public class DateFound {
- public static void main(String[] args) {
- Date[] dates = new Date[5];
-
- dates[0]=new Date(2012,9,23);
- dates[1]=new Date(2012,5,25);
- dates[2]=new Date(2012,12,4);
- dates[3]=new Date(2013,5,2);
- dates[4]=new Date(2010,3,31);
-
- //打印排序前的dates
- for(int i=0; i<dates.length;i++){
-
- System.out.println(dates[i]);
- }
-
- System.out.println();
- Date d = new Date(2012,12,4);
- // System.out.println(d);
- System.out.println();
-
- //对dates 数组排序(冒泡排序 从小到大)
- /* for(int i=0; i<dates.length-1; i++){
- for(int j=0; j<dates.length-i-1; j++){
- if(dates[j].compare(dates[j+1])==1){
- Date date = new Date();
- date = dates[j];
- dates[j]=dates[j+1];
- dates[j+1]=date;
- }
- }
- }*/
-
- dates = Date.sortDates(dates);
-
-
- /* int index = Date.binaryFound(dates,d);*/
- //打印排序后的 dates
- for(int i=0; i<dates.length;i++){
-
- System.out.println(dates[i]);
- }
- /* System.out.println(index);*/
-
-
- }
-
-
- }
- class Date {
- private int year;
- private int month;
- private int day;
-
- public Date(){}
- public Date(int year, int month, int day){
- this.year=year;
- this.month=month;
- this.day=day;
- }
-
- //比较两个Date 数的大小
- 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;
-
- }
-
-
- //查找一个 给定的 Date 对象 在已经排好序的 Date[] 数组中的索引 (二分法)
- public static int binaryFound(Date[] dates, Date date){
- int length = dates.length;
- if(length==0)return -1;
- int startPosition,endPosition,midPosition;
- startPosition =0;
- endPosition =length-1;
- midPosition =(startPosition+endPosition)/2;
- while(startPosition<=endPosition){
- if(date.compare(dates[midPosition])==0){
- return midPosition;
- }
- if(date.compare(dates[midPosition])>=0){
- startPosition=midPosition+1;
- }else{
- endPosition=midPosition-1;
- }
- midPosition =(startPosition+endPosition)/2;
- }
- //如果程序执行到这里 说明没有找到
- return -1;
-
-
-
- }
-
-
-
- //对给定数组排序
- public static Date[] sortDates(Date[] dates){
- for(int i=0; i<dates.length-1; i++){
- for(int j=0; j<dates.length-i-1; j++){
- if(dates[j].compare(dates[j+1])>1){
- Date date = new Date();
- date = dates[j];
- dates[j]=dates[j+1];
- dates[j+1]=date;
- }
- }
- }
-
- return dates;
- }
-
-
-
-
-
- public String toString(){
- return "["+year+","+month+","+day+"]";
- }
-
- }
复制代码 |