我們可以透過實作java.lang.Comparable介面來建立比較的函式。實作此介面的好處可以很方便的使用sort的函式來幫我們排序。
例:假設AccessPoint有三個參數(x, y, strength),x、y為座標,strength為訊號強度。若我們有一個AccessPoint的陣列,希望將它依訊號強度大小排序:public class AccessPoint implements Comparable
public double x, y, strength;
public AccessPoint(double x, double y, double strength) {
this.x = x;
this.y = y;
this.strength = strength;
}
public int compareTo(AccessPoint ap) {
return (strength < strength ="="">AccessPoint[] ap = {new AccessPoint(1, 2, 5), new AccessPoint(2, 3, 2)};
//遞增排序
Arrays.sort(ap);
//反向排序
Arrays.sort(ap, Collections.reverseOrder());
2008年2月24日 星期日
陣列排序
訂閱:
張貼留言 (Atom)
0 意見:
張貼留言