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

排序:Comparable接口的compareTo方法?
java核心技术(卷I)205页,源码:
以下代码,想实现按工资从小到大排序输出,能通过编译,但运行有问题,为什么呢?

import   java.util.*;

public   class   EmployeeTest
{
public   static   void   main(String[]   args)
{
Employee[]   workers   =   new   Employee[3];  
workers[0]   =   new   Employee( "tamik ",2000,1999,7,8);
workers[1]   =   new   Employee( "Yu   dan ",2800,1994,7,8);
workers[2]   =   new   Employee( "John   Rose ",2600,2001,7,8);

for(   int   nI=0;   nI <3;   nI++)
workers[nI].raiseSalary(5);


for(   Employee   e   :   workers)
System.out.println( "name= "+e.getName()
+ ",salary= "+e.getSalary()
+ ",hireDay= "+e.getHireDay());
Arrays.sort(workers);     //按工资排序
for(   Employee   e   :   workers)
System.out.println( "name= "+e.getName()
+ ",salary= "+e.getSalary()
+ ",hireDay= "+e.getHireDay());
}
}

class   Employee   implements   Comparable
{
public   Employee(String   s,   double   dbNum,   int   year,int   month,int   day)
{
name   =   s;
salary   =   dbNum;
GregorianCalendar   time=new   GregorianCalendar(year,month-1,day);
hireDay   =   time.getTime();
}
public   String   getName()
{
return   name;
}
public     Date   getHireDay()
{
return   hireDay;
}
public   double   getSalary()
{
return   salary;
}
public   void   raiseSalary(double   percent)
{
salary   *=1+percent/100;
}
public   int   compareTo(Object   other)
{
Employee   other2   =   (Employee)other;
if(this.salary   >   other2.salary)   return   1;
if(this.salary   <   other2.salary)   return   -1;
return   0;
}
private   String   name; //姓名
private   double   salary; //工资
private   Date   hireDay; //雇用日期
}

用以下代码,问题同样:
import   java.util.*;

public   class   EmployeeTest
{
public   static   void   main(String[]   args)
{
Employee[]   workers   =   new   Employee[3];  
workers[0]   =   new   Employee( "tamik ",2000,1999,7,8);
workers[1]   =   new   Employee( "Yu   dan ",2800,1994,7,8);
workers[2]   =   new   Employee( "John   Rose ",2600,2001,7,8);

for(   int   nI=0;   nI <3;   nI++)
workers[nI].raiseSalary(5);


for(   Employee   e   :   workers)
System.out.println( "name= "+e.getName()
+ ",salary= "+e.getSalary()
+ ",hireDay= "+e.getHireDay());
Arrays.sort(workers);     //按工资排序
for(   Employee   e   :   workers)
System.out.println( "name= "+e.getName()
+ ",salary= "+e.getSalary()
+ ",hireDay= "+e.getHireDay());
}
}

class   Employee   implements   Comparable <Employee>
{
public   Employee(String   s,   double   dbNum,   int   year,int   month,int   day)