我讀了一些有關compareTo()
函數的答案,但我仍然不清楚它是如何在內部工作的。compareTo()如何工作
我有下面的代碼片段,我試圖理解。
public class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
private long salary;
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public long getSalary() {
return salary;
}
public Employee(int id, String name, int age, int salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public int compareTo(Employee emp) {
//let's sort the employee based on id in ascending order
//returns a negative integer, zero, or a positive integer as this employee id
//is less than, equal to, or greater than the specified object.
return (this.id - emp.id);
}
}
而且一個CompareClass
爲:
public class CompareClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee[] empArr = new Employee[4];
empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);
//sorting employees array using Comparable interface implementation
Arrays.sort(empArr);
System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));
}
}
所以當Arrays.sort(empArr)
被調用,那麼裏面compareTo()
,這是this.id
並且是emp.id
?
基本上我試圖理解,當compareTo()
被調用時,然後employee
對象empArr
成爲當前對象,然後,與哪個對象進行比較。
return (this.id - emp.id);
那麼,什麼是this
和emp
?
'sort'方法在排序期間需要比較的數組實例中調用'compareTo'。沒有「當前對象」,這是由排序算法的實現驅動的。 – pvg
它可以像任何其他功能一樣工作。它在某個實例上被調用,並且它有一個參數。 – SLaks
如果你把它寫成'public int compareTo(Employee that)',你會發現它更容易理解。你所做的就是將'this'與'that'進行比較。 – EJP