java.util.Comparator

java.util.Comparator
1:java.util.Comparator是一个接口,只包含两个方法:

方法摘要
int
compare(T o1, T o2)
比较用来排序的两个参数。
boolean
equals(Object obj)
指示是否其他对象“等于”此 Comparator。

2:在JDK中对java.util.Comparator的功能的解释为:“强行对某些对象 collection 进行整体排序”。
具体的实现是在compare(T o1, T o2)方法中自定义排序算法,然后将Comparator对象(实现了java.util.Comparator接口的对象)作为一个参数传递给欲排序对象collection的某些排序方法。某些排序方法指的是能够接受java.util.Comparator参数的方法,比如:java.util. Arrays的public static void sort(Object[] a, Comparator c)
3:典型例程:

import java.util.Comparator;

public class ByWeightComparator implements Comparator

{

/**

* Compare two Trucks by weight. Callback for sort or TreeMap.

* effectively returns a-b; orders by ascending weight

*

* @param pFirst first object a to be compared

*

* @param pSecond second object b to be compared

*

* @return +1 if a>b, 0 if a=b, -1 if a<b

*/

public final int compare ( Object pFirst, Object pSecond )

{

long aFirstWeight = ( (Truck)pFirst ).weight;

long aSecondWeight = ( (Truck)pSecond ).weight;

/* need signum to convert long to int, (int)will not do! */

return signum( aFirstWeight - aSecondWeight );

} // end compare

/**

* Collapse number down to +1 0 or -1 depending on sign.

* Typically used in compare routines to collapse a difference

* of two longs to an int.

*

* @param diff usually represents the difference of two long.

*

* @return signum of diff, +1, 0 or -1.

*/

public static final int signum ( long diff )

{

if ( diff > 0 ) return 1;

if ( diff < 0 ) return -1;

else return 0;

} // end signum

} // end class ByWeight



如果你对数据结构和算法都很熟悉,那你大可自己编写高效的排序方法。但是如果你对此不是很熟的话, JDK 中为你提供了非常方便的类: java.util.Arrays 和 java.util.Collection 。
其中,java.util.Arrays 主要是对对象数组进行处理,包括对对象数组填值、查找、比较、排序等。而 java.util.Collection 也具有同样的功能,只是它所处理的对象是对象链表。而且它们的这些方法都是静态的,可以直接调用。下面是具体的例子:

//给对象数组排序
Object[] objects = getObjectArray(); //取得你要排序的对象数组
Arrays.sort( objects );

//给对象链表排序
List objectList = getObjectList(); //取得你要排序的对象链表
Collections.sort( objectList );

注意:使用上述方法时,对象数组或对象链表中的对象必须实现接口:java.lang.Comparable

用这样方法就可以完成非常高效的排序方法。对于 Arrays 和 Collections 更为详细的使用方法请参阅 JDK 文档。

没有评论: