CSDN博客

img lde1208

一个会排序的Vector

发表于2004/7/18 11:21:00  699人阅读


import?java.util.*;
interface?Compare?{
??boolean?lessThan(Object?lhs,?Object?rhs);
??boolean?lessThanOrEqual(Object?lhs,?Object?rhs);
}
////////////////////////////////////////////////////////////////////
class?SortVector?extends?Vector?{
??private?Compare?compare;?
//?To?hold?the?callback
??public?SortVector(Compare?comp)?{
????compare?=?comp;
??}
??public?void?sort()?{
????quickSort(0,?size()?-?1);
??}
??
//?快速排序
??private?void?quickSort(int?left,?int?right)?{
????if(right?>?left)?{
??????Object?o1?=?elementAt(right);
??????int?i?=?left?-?1;
??????int?j?=?right;
??????while(true)?{
????????while(compare.lessThan(
??????????????elementAt(++i),?o1));
????????while(j?>?0)
??????????if(compare.lessThanOrEqual(elementAt(--j),?o1))
???????????????break;?
//?out?of?while
????????if(i?>=?j)?break;
????????swap(i,?j);
??????}
??????swap(i?,?right);
??????quickSort(left,?i-1);
??????quickSort(i+1,?right);
????}
??}
??
//交换位置
??private?void?swap(int?loc1,?int?loc2)?{
????Object?tmp?=?elementAt(loc1);
????setElementAt(elementAt(loc2),?loc1);
????setElementAt(tmp,?loc2);
??}
}
////////////////////////////////////////////////////////////////////
public?class?StringSortTest?{
??
//?自定义比较规则
??static?class?StringCompare?implements?Compare?{
????public?boolean?lessThan(Object?l,?Object?r)?{
??????return?((String)l).toLowerCase().compareTo(
????????((String)r).toLowerCase())?????}
????public?boolean?
????lessThanOrEqual(Object?l,?Object?r)?{
??????return?((String)l).toLowerCase().compareTo(
????????((String)r).toLowerCase())?<=?0;
????}
??}
??public?static?void?main(String[]?args)?{
????SortVector?sv?=?
??????new?SortVector(new?StringCompare());
????
//?添加Element
????sv.addElement(
"d");
????sv.addElement(
"A");
????sv.addElement(
"C");
????sv.addElement(
"c");
????
//?排序
????sv.sort();
????Enumeration?e?=?sv.elements();
????
//?输出结果
????while(e.hasMoreElements())
??????System.out.println(e.nextElement());
??}
}

代码详解:
因为我们要做一个会排序的Vector,所以class?SortVector?extends?Vector.?
interface?Compare
的作用是定义统一的比较大小的接口.

注意class?StringCompare?,在它里面定义了String比较大小的规则,?以后我们如何想写个XXXXVector,?只要在写个class?XXXXXCompare?implements?Compare就好了.

0 0

相关博文

我的热门文章

img
取 消
img