有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何实现通用比较器?

因此,我尝试将插入排序与必须传入的通用比较器一起使用。我无法更改方法名称。我将如何实现一个比较器来传递到insertionSort方法中?我不熟悉java和面向对象编程

该测试只是一个junit测试

public class SortUtil {


public static <T> void insertionSort(ArrayList<T> dataSet, int left, int right, Comparator<? super T> Comparator)
{

    for(int i = left + 1; i <= right; i++)
    {
        T item = dataSet.get(i);

        int j;
        if (dataSet != null)
        {
        for(j = i - 1; (j >= left) && (Comparator.compare(dataSet.get(j), item)) > 0; j--)
        {
            dataSet.set(j + 1, dataSet.get(j)) ;
        }
        dataSet.set(j + 1, item);
        }
    }

}


public void test() {        
    Comparator<? super T> Comp = null;

    ArrayList<T> temp = (ArrayList<T>) SortUtil.generateBestCase(10);

    SortUtil.insertionSort(temp, 0, temp.size(), Comp);






}

}

共 (1) 个答案

  1. # 1 楼答案

    insertionSort()是通用的。它使用Ttest()不是。它应该使用您想要测试的任何特定类型。在test()中,您不需要创建Comparator<? super T>,您可以创建Comparator<Integer>Comparator<String>或您喜欢的任何其他随机特定的Comparator,唯一的要求是类型必须与ArrayList temp使用的类型相同或是其父类型(同样应该是ArrayList<Integer>ArrayList<String>,等等)

    要创建自定义Comparator<Integer>,请执行以下操作:

    Comparator<Integer> comp = new Comparator<Integer>() {
        public int compare(Integer i1, Integer i2) {
            // Your code here. Check the documentation for how this should behave.
        }
    };