一、數組排序
import com.ObjectAnalyzer;
public class Employee implements Comparable<Employee>{
private String name;
private double salary;
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) {
return Double.compare(salary, other.salary);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return new ObjectAnalyzer().toString(this);
}
}
調用方法:
public static void array(){
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000);
Arrays.sort(staff);
System.out.println(Arrays.toString(staff));
}
public static void array(){
Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 35000);
staff[1] = new Employee("Carl Cracker", 75000);
staff[2] = new Employee("Tony Tester", 38000);
Arrays.sort(staff , new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
return Double.compare(o1.getSalary(), o2.getSalary());
}
});
System.out.println(Arrays.toString(staff));
}
備註:通過調用Arrays.sort()方法來對數組進行排序,但是內部比較兩個對象時有兩種方式:
1>對象類實現Comparable接口中的compareTo方法。
2>調用Arrays.sort(Employee[] a,Comparator<? superEmployee> c)方法,並且實現compare方法。
注:打印數組中的內容調用了Arrays.toString()方法,本質上一次調用每個對象的toString方法,所以爲了打印適當的信息,需要重寫對象類的toString方法。
二、集合排序
對象類如上
調用方法:
public static void collection() {
List<Employee> staffList = new ArrayList<>();
staffList.add(new Employee("Harry Hacker", 35000));
staffList.add(new Employee("Carl Cracker", 75000));
staffList.add(new Employee("Tony Tester", 38000));
Collections.sort(staffList);
System.out.println(staffList.toString());
}
public static void collection() {
List<Employee> staffList = new ArrayList<>();
staffList.add(new Employee("Harry Hacker", 35000));
staffList.add(new Employee("Carl Cracker", 75000));
staffList.add(new Employee("Tony Tester", 38000));
Collections.sort(staffList, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
return Double.compare(o1.getSalary(), o2.getSalary());
}
});
System.out.println(staffList.toString());
}
備註:通過對比可以發現對於集合的處理與數組類似,通過調用Collections.sort()方法處理,而且排序的方式也是相同的兩種。查看內部代碼如下:
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}
public static <T> void sort(List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}
本質上對於集合的排序是通過將集合轉換爲數組排序的。