下面是书上的一个程序.
import java.util.*;
public class Test
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
staff[0] = new Employee("abc", 5000);
staff[1] = new Employee("efg", 2000);
staff[2] = new Employee("opq", 3500);
Arrays.sort(staff);
for(Employee e: staff)
{
System.out.println("name = " + e.getName() + ", and his salary is "+ e.getSalary());
}
}
}
class Employee implements Comparable<Employee>
{
public Employee(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public int compareTo(Employee other)
{
if(salary < other.salary)
{
return -1;
}
if(salary > other.salary)
{
return 1;
}
return 0;
}
private String name ;
private double salary;
}
我对这一步
public int compareTo(Employee other)
{
if(salary < other.salary)
{
return -1;
}
if(salary > other.salary)
{
return 1;
}
return 0;
}
中的salary的比较是说前一个雇员的薪水与后一个雇员的薪水进行比较,但是我不明白的是,从哪里可以看出是前一个雇员与后一个雇员的薪水进行比较?尤其是前一个salary没有任何修饰词。C语言中好歹用salary[i-1]与salary[i]来看出前后。
------解决方案--------------------
你本身这个类调用这个方法需要new对象吧,前一个salary就是他的
------解决方案--------------------
主动调用该方法的实例化Employee对象就是“前一个”
传入的实例化Employee对象参数就是“后一个”
------解决方案--------------------
public int compareTo(Employee other)
{
if(salary < other.salary)
{
return -1;
}
if(salary > other.salary)
{
return 1;
}
return 0;
}
这边的salary其实是隐藏了一个关键字的就是this,其实就是this.salary,this指的是当前调用这个方法的对象,如果要明白如果调用compareTo方法的话,你看下Array.sort的源码吧
------解决方案--------------------
public int compareTo(Employee other)
{
if(this.salary < other.salary)
{
return -1;
}
if(this.salary > other.salary)
{
return 1;
}
return 0;
}
------解决方案--------------------
public int compareTo(Employee other)
{
if(this.salary < other.salary)
{
return -1;
}
if(this.salary > other.salary)
{
return 1;
}