Jumbala
Jumbala

Reputation: 4944

How to pass any Class that implements a particular interface as a parameter and use its methods?

I created my own "LinkedList" class that can take in objects specified with a generic.

In that Class, I want to have a sort(ComparatorObject) method that takes in an object whose Class implements Comparator.

The reason for that is that for my test objects in particular, Shapes, I want to see if I can sort them by various fields selected by the user, such as the shapes' areas, perimeter, type, etc.

Right now, one of my comparator classes is defined like this:

public class Comparator_Area implements Comparator<Shape>{

@Override
public int compare(Shape shape1, Shape shape2) {
    int valueToReturn = 0;

    if(shape1.getArea() < shape2.getArea()){
        valueToReturn = -1;
    }
    else if(shape1.getArea() < shape2.getArea()){
        valueToReturn = 1;
    }

    return valueToReturn;
}
}

And in my LinkedList Class, my sort method is defined like this (I don't know if it's correct, but it's what I found while looking up how to do this):

public void sort(Class<? extends Comparator<E>> comparator){

}

Naturally, I'd like to be able to use something like this in the sort method:

comparator.compare(shape1, shape2);

But I can't use "compare" and I don't really know how I'm supposed to accomplish this.

Upvotes: 0

Views: 1844

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You should send a Comparator object as parameter in your sort method:

public void sort(Comparator<Shape> comparator){

}

This is assuming your LinkedList class is only of Shapes. If you have a generic LinkedList implementation, then you can pass a Comparator<T>:

public class MyLinkedList<T> {
    //other methods...

    public void sort(Comparator<T> comparator){

    }
}

Upvotes: 3

LuGo
LuGo

Reputation: 5045

You are passing the Class object as parameter. Try the following instead:

public void sort(Comparator<T> comparator){

}

where T is the generic type of your LinkedList.

Upvotes: 1

Related Questions