Posted on 2007-10-19 10:28
久城 阅读(4374)
评论(1) 编辑 收藏 所属分类:
JavaTest
早上来公司的路上,路边一片绿油油的小草上都披上了一身白霜。树叶突然间变黄了,我终于完全的感觉到了,秋的气息。
参照:http://www.blogjava.net/realsmy/archive/2007/10/17/153435.html,继续这个问题,用JAVA实现对二维数组的排序。顺便学习了一下Comparable接口。
/** *//**
* Class Name : YW2_Test02.java
* Purpose : 对二维数组按列排序
*
* @author realsmy
* @since 2007/10/19
*
* Copyright realsmy. All rights reserved.
*/
package com.neusoft.test;
import java.util.*;
public class YW5_Test02 {
private int ary[][];
private MySort mySort;
// 数据初始化
public YW5_Test02(int ary[][], MySort mySort) {
this.ary = ary;
this.mySort = mySort;
}
// 排序
public void sort() {
Arrays.sort(ary, mySort);
printArray();
}
// 打印
private void printArray() {
System.out.println("---------Begin---------");
for (int[] a : ary) {
for (int i : a)
System.out.print(i + " ");
System.out.println();
}
System.out.println("---------End---------");
}
public static void main(String[] arg) throws Exception {
//int ary[][] = { {1,5,456,6,89}, {2,51,515,32,15}, {3,45,68,24,6}, {4,822,4,88,462}, {5,87,44,865,99}};
int ary[][] = RandomArray.GetArray(4, 5);
new YW5_Test02(ary, new MySort(0,"asc")).sort();
new YW5_Test02(ary, new MySort(1,"asc")).sort();
new YW5_Test02(ary, new MySort(2,"desc")).sort();
new YW5_Test02(ary, new MySort(3,"asc")).sort();
new YW5_Test02(ary, new MySort(4,"desc")).sort();
}
}
class MySort implements Comparator<int[]> {
// 想要进行排序的列数
private int columnNumber;
// 排序方式:desc or asc
private String order;
public MySort(int columnNumber, String order) {
this.columnNumber = columnNumber;
this.order = order;
}
public int compare(int a[], int b[]) {
if ("desc".equals(order)) {
return b[columnNumber] - a[columnNumber];
} else {
return a[columnNumber] - b[columnNumber];
}
}
}
class RandomArray{
// 随机生成二维数组
public static int[][] GetArray(int row, int column) {
Random random = new Random();
int i, j;
int[][] array;
if ((row > 0) && (column > 0))
array = new int[row][column];
else
array = new int[1][1];
for (i = 0; i < array.length; i++)
for (j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(100);
}
return array;
}
}
Comparable接口第一次接触,感觉很好。
欢迎来访!^.^!
本BLOG仅用于个人学习交流!
目的在于记录个人成长.
所有文字均属于个人理解.
如有错误,望多多指教!不胜感激!