Mardymar
Mardymar

Reputation: 419

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); that says classname cannot be applied to 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;
    }
}

Upvotes: 1

Views: 1189

Answers (2)

BValluri
BValluri

Reputation: 956

class ShapeComparator implements Comparator<Shape> {

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

        return 0;
    }

}

Upvotes: 0

radoh
radoh

Reputation: 4809

You need to pass it an instance of a Comparator, e.g.

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

Upvotes: 1

Related Questions