在收集物件之後,對物件進行排序是常用的動作,你不用親自實作排序演算法,java.util.Collections提供有sort()方法,由於必須有索引才能進行排序,因此Collections的sort()方法接受List實作物件。
實際開發總是不斷有意外,如果你的物件無法實作Comparable
呢?也許你拿不到原始碼!也許你不能修改原始碼!舉個例子來說,String
本身有實作Comparable
,所以你可以如下排序:
public static void main(String[] args) {
List words = Arrays.asList("B", "X", "A", "M", "F", "W", "O");
Collections.sort(words);
System.out.println(words);
}
Out:
[A, B, F, M, O, W, X]
Comparator用在對象外面,相當於定義了一套排序演算法來排序。
實做Comparator
●假設員工預設是以員工編號排序,但下列情況
--請以職稱排序:
import java.util.Comparator;
public class Employee implements Comparator<Employee> {
private int Id;
private String Name;
@Override
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
//return (o1.getName().compareTo(o2.getName()))*-1; //順序會顛倒
}
public int getId() {
return Id;
}
public String getName() {
return Name;
}
public Employee() {
}
public Employee(int Id, String Name) {
this.Id = Id;
this.Name = Name;
}
@Override
public String toString() {
return "ID:" + this.getId() + " Name:" + this.getName();
}
}
public class Test2 {
public static void main(String[] args) {
List<Employee> words = Arrays.asList(new Employee(1,"B"),new Employee(2,"A"));
Collections.sort(words, new Employee());
System.out.println(words);
}
}
Out:
[ID:2 Name:A, ID:1 Name:B]
參考資料: https://openhome.cc/Gossip/Java/ComparableComparator.html
以中文名字排序:
import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;
public class Employee implements Comparator<Employee> {
private int Id;
private String Name;
@Override
public int compare(Employee o1, Employee o2) {
Locale locale = new Locale(
System.getProperty("user.language"),//ZH 中華音譯
System.getProperty("user.country"));//TW 台灣
Collator com = Collator.getInstance(locale);
return com.compare(o1.getName(), o2.getName());
}
public int getId() {
return Id;
}
public String getName() {
return Name;
}
public Employee() {
}
public Employee(int Id, String Name) {
this.Id = Id;
this.Name = Name;
}
@Override
public String toString() {
return "ID:" + this.getId() + " Name:" + this.getName();
}
}
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
List<Employee> words = Arrays.asList(new Employee(1,"林"),new Employee(2,"王"));
Collections.sort(words, new Employee());
System.out.println(words);
}
}
Out:
[ID:2 Name:王, ID:1 Name:林]