一种从二维数组中对每个字符进行排序的方法。将看到通过更改 ArrayDatum 的数据成员以及如何实现 Cmpr,您可以以不同的方式对其他对象进行排序,因此可以有 Cmpr2、Cmpr3 ....
public class ArrayDatum <T>{
private int locX; //probably do not need this -> original location but keot it for future use
private int locY;
private T data;
public ArrayDatum(T dat, int x, int y){
data = dat;
locX = x;
locY = y;
}
public int getLocationX(){
return locX;
}
public void setLocationX(int x){
locX = x;
}
public int getLocationY(){
return locY;
}
public void setLocationY(int y){
locY = y;
}
public T getData(){
return data;
}
public void setData(T d){
data = d;
}
}
//比较器
import java.util.Comparator;
/**
* Comparator for ArrayDatum<String>
* Else not predictable
*/
public class Cmpr implements Comparator{
public int compare(Object c1, Object b1){
ArrayDatum c = (ArrayDatum )c1;
ArrayDatum b = (ArrayDatum )b1;
if(c == null || b == null) return 0;
return c.getData().toString().compareTo(b.getData().toString());
}
}
//测试应用
import java.util.*;
public class Tst {
public static void main(String[] args){
String[][] rows = {
{"M","O","N","K","E","Y"},
{"D","O","N","K","E","Y"},
{"M","A","K","E"},
{"M","U","C","K","Y"},
{"C","O","O","K","Y"},
};
prnt(rows);
List<ArrayDatum> dat = new ArrayList<ArrayDatum>();
for(int i =0; i < rows.length; i++){
for(int j =0; j < rows[i].length; j++){
ArrayDatum<String> dt = new ArrayDatum<String>(rows[i][j], i, j);
dat.add(dt);
}
}
Cmpr cmpr = new Cmpr();
Collections.sort(dat, cmpr);
int sz = dat.size();
System.out.println("------\nsort\n");
for(int i =0; i < sz; i++){
System.out.print(dat.get(i).getData() + " " );
}
//for(int i =0; i < sz; i++){
// ArrayDatum d = dat.get(i);
// rows[d.getLocationX()][d.getLocationY()] = d.getData().toString();
//}
int loc = 0;
/*
lay them into original array again
for(int i =0; i < rows.length; i++){
for(int j =0; j < rows[i].length; j++){
rows[i][j] = dat.get(loc).getData().toString();
loc++;
}
}
prnt(rows);*/
}
static void prnt(String[][] rows){
for(int i =0; i < rows.length; i++){
for(int j =0; j < rows[i].length; j++){
System.out.print(rows[i][j]);
}
System.out.println();
}
}
}