import java.util.*;
public class Main {
public static void main(String[] args) {
String[][] arr = {{"B","啊","20%"},
{"C","中","12%"},
{"A","我","55%"}} ;
//缺省(按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;
}
}
}
阅读(1679) | 评论(1) | 转发(0) |