使用带有泛型的比较器

时间:2016-02-17 18:35:03

标签: java generics comparator

我正在尝试使用泛型方法对数组进行排序。我在Lab6Sort(octArr);收到错误消息,指出 classname 无法应用于Shape []。

 public static void main(String[] args) {
    Shape[] octArr = new Shape[10];

    for(int i = 0; i < 10; i++){
        octArr[i] = new L6MPerRegOct(Math.floor(Math.random() * 1000) / 10);
    }

    Lab6Sort(octArr);
}
.
.
 public static <AnyType> void Lab6Sort (AnyType [] arr, Comparator<? super AnyType> cmp)

似乎我需要第二个论点,但我不确定这应该是什么。

以下是完整的代码:

public class L6MPerRegOct extends Shape {
    public static void main(String[] args) {
        Shape[] octArr = new Shape[10];

        for(int i = 0; i < 10; i++){
            octArr[i] = new L6MPerRegOct(Math.floor(Math.random() * 1000) / 10);
        }

        Lab6Sort(octArr);

    }

    private double sideLength;

    public L6MPerRegOct(double len){
        sideLength = len;
    }

    public double area(){
        return 2 * sideLength*sideLength * (1 + Math.sqrt(2));
    }
    public static <AnyType> void Lab6Sort (AnyType [] arr, Comparator<? super AnyType> cmp)
    {
        int j, minIndex, n = arr.length;
        AnyType temp;

        for ( int index = 0; index < n - 1; index++ ) {
            minIndex = index;

            for (j = index + 1; j < n; j++) {
                if (cmp.compare(arr[index], arr[minIndex]) < 0)
                    minIndex = j;
            }

            if (minIndex != index) {
                temp = arr[index];

                arr[index] = arr[minIndex];

                arr[minIndex] = temp;
        }
    }

public abstract class Shape implements Comparable<Shape>
{
    public abstract double area( );
    public abstract double perimeter( );

    public int compareTo( Shape rhs )
    {
        double diff = area( ) - rhs.area( );
        if( diff == 0 )
            return 0;
        else if( diff < 0 )
            return -1;
        else
            return 1;
    }

    public double semiperimeter( )
    {
        return perimeter( ) / 2;
    }
}

2 个答案:

答案 0 :(得分:1)

您需要传递一个Comparator的实例,例如

Lab6Sort(octArr, new Comparator<Shape>() {
    @Override
    public int compare(Shape o1, Shape o2) {
        return 0;
    }
});

如果要重用它,可以在另一个类中定义Comparator

public class ShapeComparator implements Comparator<Shape> {
    @Override
    public int compare(Shape o1, Shape o2) {
        return 0;
    }
}

答案 1 :(得分:0)

class ShapeComparator implements Comparator<Shape> {

    @Override
    public int compare(Shape o1, Shape o2) {

        return 0;
    }

}