简体   繁体   中英

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.

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 Shape s. 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){

    }
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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