二维数组排序实例:
import java.util.*; public class TwoDimArrayTest { public static void main(String[] args) { String[][] arr = {{"B","Z","K"}, {"C","X","L"}, {"A","Y","M"}} ; //缺省(按0列升序) Arrays.sort(arr, new TwoDimArrayComparator()); printArray(arr); //按0列降序 Arrays.sort(arr, new TwoDimArrayComparator(0,-1)); printArray(arr); //按1列升序 Arrays.sort(arr, new TwoDimArrayComparator(1)); printArray(arr); //按1列降序 Arrays.sort(arr, new TwoDimArrayComparator(1,-1)); printArray(arr); //按2列升序 Arrays.sort(arr, new TwoDimArrayComparator(2)); printArray(arr); //按2列降序 Arrays.sort(arr, new TwoDimArrayComparator(2,-1)); printArray(arr); } public static void printArray(String[][] arr) { for (int i= 0; i< arr.length ; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] +"\t"); } System.out.println(); } System.out.println("======================"); } }
class TwoDimArrayComparator implements Comparator{ private int keyColumn = 0; private int sortOrder = 1; public TwoDimArrayComparator () {} public TwoDimArrayComparator (int keyColumn) { this.keyColumn = keyColumn; } public TwoDimArrayComparator (int keyColumn,int sortOrder) { this.keyColumn = keyColumn; this.sortOrder = sortOrder; } public int compare(Object a, Object b) { if (a instanceof String[]) { return sortOrder * ((String[])a)[keyColumn].compareTo(((String[])b)[keyColumn]); } else if (a instanceof int[]){ return sortOrder * (((int[])a)[keyColumn] - ((int[])b)[keyColumn]); } else { return 0; } } }
运行结果:
C:\java>java TwoDimArrayTest
A Y M
B Z K
C X L
======================
C X L
B Z K
A Y M
======================
C X L
A Y M
B Z K
======================
B Z K
A Y M
C X L
======================
B Z K
C X L
A Y M
======================
A Y M
C X L
B Z K
======================
本文转自kenty博客园博客,原文链接http://www.cnblogs.com/kentyshang/archive/2007/07/04/805334.html如需转载请自行联系原作者
kenty