简体   繁体   English

将比较器与泛型一起使用

[英]Using a comparator with generics

I am trying to use a generic method to sort an array. 我正在尝试使用通用方法对数组进行排序。 I am receiving an error on Lab6Sort(octArr); 我在Lab6Sort(octArr);上收到错误Lab6Sort(octArr); that says classname cannot be applied to Shape[]. 类名不能应用于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)

It seems that I need a second argument, but I am unsure what this should be. 似乎我需要第二个论点,但是我不确定这应该是什么。

Here is the complete code: 这是完整的代码:

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;
    }
}

You need to pass it an instance of a Comparator , eg 您需要向其传递Comparator的实例,例如

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

Or define the Comparator in a separate class, if you want to reuse it 如果要重用它,或者在单独的类中定义比较器

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

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

        return 0;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM