Java 使用比较器对象作为参数的通用insertionSort?
如果给我这个方法头:Java 使用比较器对象作为参数的通用insertionSort?,java,generics,comparator,superclass,insertion-sort,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 }
/**
* 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
}
/**
*此通用方法使用插入排序和输入比较器对象对输入数组进行排序。
*/
公共静态void insertionSort(T[]数组,Comparator试试这个
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; }}
公共静态
void insertionsorgeneric(T[]a,Comparator您应该传入一个Comparator
对象
int compare(T obj1, T obj2)
用谷歌搜索一些例子,例如,你根本没有回答OP的问题。在你的代码中使用这个片段,它会有防御作用,只需使用循环打印a。我在问我是否需要制作一个比较器对象,告诉我如何比较泛型数组中的元素。@ProjectDefy除非你将T
约束为本质上可比,即,公共静态…
,那么是的,您需要指定一些外部方法来比较数组元素。