使用Comparator对象作为参数的通用插入?

时间:2016-02-07 07:56:41

标签: java generics comparator superclass insertion-sort

如果我给这个方法标题:

/**
 * This generic method sorts the input array using an insertion sort and the input Comparator object.
 */
public static <T> void insertionSort(T[] array , Comparator<? super T> comparatorObj){

        // Implement method
}

对于参数中的Comparator<? super T> comparatorObj部分,我是否想要制作一个比较对象方法,告诉它在insertSort参数中使用它时应该如何进行比较?

2 个答案:

答案 0 :(得分:-1)

您应该传入Comparator个对象。基本上,您只需要实现方法

int compare(T obj1, T obj2)

谷歌的一些例子,例如http://www.tutorialspoint.com/java/java_using_comparator.htm

答案 1 :(得分:-2)

试试这个

public static <T>
void insertionSortGeneric(T[] a, Comparator<? super T> c) {
   for (int i=0; i < a.length; i++) {
    /* Insert a[i] into the sorted sublist */
    T v = a[i];
    int j;
    for (j = i - 1; j >= 0; j--) {
        if (c.compare(a[j], v) <= 0) break;
        a[j + 1] = a[j];
    }
    a[j + 1] = v; }}