java.util.Comparator
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 文档。
没有评论:
发表评论