Java中可以排序的工具類和接口共有五個SortedMap 、SortedSet、TreeMap 、TreeSet和Collections,Collections中需要顯式調用sort()方法。
事例如下:
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- import myUtil.myArrayComparator;
- import java.util.Map;
- import java.util.HashMap;
- import java.util.TreeMap;
- import java.util.Collection;
- import java.util.Iterator;
- import myUtil.myMapComparator;
-
- public class mySort {
- public mySort() {
- }
-
- /**
- * 數組的中文排序
- */
- public void arraySort() {
-
- String[] sortArray = {"中山", "汕尾", "廣州", "汕頭", "陽江"};
- Arrays.sort(sortArray);
- for (int i = 0; i < 5; i++) {
- System.out.println( (String) sortArray[i]);
- }
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- import myUtil.myArrayComparator;
- import java.util.Map;
- import java.util.HashMap;
- import java.util.TreeMap;
- import java.util.Collection;
- import java.util.Iterator;
- import myUtil.myMapComparator;
-
- public class mySort {
- public mySort() {
- }
-
- /**
- * 數組的中文排序
- */
- public void arraySort() {
-
- String[] sortArray = {"中山", "汕尾", "廣州", "汕頭", "陽江"};
- Arrays.sort(sortArray);
- for (int i = 0; i < 5; i++) {
- System.out.println( (String) sortArray[i]);
- }
//結果排序為:中山,廣州,汕頭,汕尾,陽江。按照每個單詞最後一個字母的降序進行排列。
- String[] reverseArray = {"中山", "汕尾", "廣州", "汕頭", "陽江"};
- Collections.reverse(Arrays.asList(reverseArray));
- for (int i = 0; i < 5; i++) {
- System.out.println( (String) reverseArray[i]);
- }
- String[] reverseArray = {"中山", "汕尾", "廣州", "汕頭", "陽江"};
- Collections.reverse(Arrays.asList(reverseArray));
- for (int i = 0; i < 5; i++) {
- System.out.println( (String) reverseArray[i]);
- }
//結果排序為:陽江,汕頭,廣州,汕尾,中山。Coleections的反序(reverse)是指單詞進行首末對換