日期:2014-05-20  浏览次数:20840 次

java函数返回数组的问题,新手请教

public class Test3{
public static void main(String args[]){
Date date2[];
date2=new Date[5];
date2[0]=new Date(2013,1,4);
date2[1]=new Date(2013,2,2);
date2[2]=new Date(2013,1,3);
date2[3]=new Date(2013,1,1);
date2[4]=new Date(2013,2,5);
date2=date2.compare2(date2);//错误。。。。
date2.compare2(date2);//也是错误,为什么,那么该如何指向返回的数组呢
                  date2=&date2.compare2(date2);//错误。。。。
for(int i=0;i<date2.length;i++){
System.out.println(date2[i]);
}
}
}
class Date{
int year,month,day;
Date(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
}
public int compare(Date date){
                  ....省略
}
public Date[] compare2(Date[] a){
Date temp;
for(int i=0;i<a.length;i++)
for(int j=i+1;j<a.length;j++){
if(a[i].compare(a[j])==1){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
return a;
}
public String toString(){
return(year+"-"+month+"-"+day);
}
}

------解决方案--------------------
你的compare2这能被Date实例调用,而你用的是Date实例的数组去调用,那能行吗?date2[1].compare2这样可以的
------解决方案--------------------
public class Test3{
public static void main(String args[]){
Date date2[];
date2=new Date[5];
date2[0]=new Date(2013,1,4);
date2[1]=new Date(2013,2,2);
date2[2]=new Date(2013,1,3);
date2[3]=new Date(2013,1,1);
date2[4]=new Date(2013,2,5);
date2=new Date().compare2(date2);//改这里就可以了...
new Date().compare2(date2);//也是错误,为什么,那么该如何指向返回的数组呢
                // date2=&date2.compare2(date2);//错误。。。。
for(int i=0;i<date2.length;i++){
System.out.println(date2[i]);
}
}
}
class Date{
int year,month,day;
Date(int year,int month,int day){
this.year=year;
this.month=month;
this.day=day;
}
public int compare(Date date){
                  ....省略
}
public Date[] compare2(Date[] a){
Date temp;
for(int i=0;i<a.length;i++)
for(int j=i+1;j<a.length;j++){
if(a[i].compare(a[j])==1){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
return a;
}
public String toString(){
return(year+"-"+month+"-"+day);
}
}

注意Date类不要Package错jar,最好起类名不要用这种关键字...
------解决方案--------------------
Date本身就是关键字
这样用会出一些莫名其妙的错误的