本方法只能針對 List<Integer> 及 List<String> 進行『升冪排序』
詳見<範例程式 1>及 <範例程式 2>
若要針對其它自訂 Object 物件進行排序
則必須將自訂 Object 宣告為實作 Comparator 之物件,並於 Class 實作 Compare() 方法
實作時可自定排序方式為『升冪』或『降冪』
詳見<範例程式 3>
本例子為升冪,修改 compare() 方法之第一個 if 判斷為
Long.parseLong(value2) - Long.parseLong(value1) > 0
即可轉為降冪排序
--------------範例程式 1--------------
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(1);
list.add(3);
list.add(2);
Collections.sort(list);
for (int value : list) {
System.out.println(value);
}
}
範例程式 1 執行結果 :
1
2
3
4
--------------範例程式 2--------------
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("d");
list.add("a");
list.add("c");
list.add("b");
Collections.sort(list);
for (String value : list) {
System.out.println(value);
}
}
範例程式 2 執行結果 :
a
b
c
d
--------------範例程式 3--------------
<3-1>
import java.util.Comparator;
public class TestBean implements Comparator
{
String modifyDate;
double value;
public TestBean() {
}
public TestBean(String
lastModifyDate, double averageTestValue) {
this.modifyDate = lastModifyDate;
this.value =
averageTestValue;
}
@Override
public int compare(Object
obj1, Object obj2) {
TestBean
bean1 = (TestBean) obj1;
TestBean
bean2 = (TestBean) obj2;
String
value1 = bean1.getModifyDate();
String
value2 = bean2.getModifyDate();
if (Long.parseLong(value1)
- Long.parseLong(value2) > 0) {
return 1;
} else if
(value1.equals(value2)) {
return 0;
} else {
return -1;
}
}
public String
getModifyDate() {
return modifyDate;
}
public void
setModifyDate(String modifyDate) {
this.modifyDate = modifyDate;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
<3-2>
import java.util.ArrayList;
import java.util.ArrayList;
import
java.util.Collections;
import
java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[]
args) {
List<TestBean> testList = new ArrayList<TestBean>();
testList.add(new TestBean("20130314000000", 1));
testList.add(new TestBean("20130311000000", 2));
testList.add(new TestBean("20130313000000", 3));
testList.add(new TestBean("20130312130345", 4));
testList.add(new TestBean("20130312110435", 5));
Comparator
comp = new TestBean();
Collections.sort(testList,
comp);
for (TestBean a :
testList) {
System.out.println(a.getModifyDate()
+ ", " + a.getValue());
}
}
}
範例程式 3 執行結果 :
20130311000000, 2.0
20130312110435, 5.0
20130312130345, 4.0
20130313000000, 3.0
20130314000000, 1.0
20130312110435, 5.0
20130312130345, 4.0
20130313000000, 3.0
20130314000000, 1.0