0

我收到以下编译错误:

The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (T[], Comparator<capture#1-of ? extends T>) Main.java   /Sorting/src/com/kash/test  line 11
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (T[], Comparator<capture#2-of ? super T>)   Main.java   /Sorting/src/com/kash/test  line 15
The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (T[], Comparator<T>)    Main.java   /Sorting/src/com/kash/test  line 19

当我编译(在 Eclipse Juno 中使用 JDK 1.7.0)此代码时:

package com.kash.test;

import java.util.Collections;
import java.util.Comparator;

// 3 attempts to write a wrapper over: Collections' method
//      public static <T> void sort(List<T> list, Comparator<? super T> c)
public class Main {

    public static <T> void sort1(T[] array, Comparator<? extends T> c) {
        Collections.sort(array, c); // line 11
    }

    public static <T> void sort2(T[] array, Comparator<? super T> c) {
        Collections.sort(array, c); // line 15
    }

    public static <T> void sort3(T[] array, Comparator<T> c) {
        Collections.sort(array, c); // line 19
    }

    public static void main(String[] args) {

    }
}

我已阅读以下内容,但并不太了解。有什么帮助吗?

- 编辑 -

对于那些想知道我为什么做这么愚蠢的事情的挑剔的人。如果你不在乎我为什么要这样做,那就别打扰其他人了。

为什么?

我正在编写以下接口的几个实现(例如 Quick、Insertion、Heap、Mixed、Intro、Bubble...):

package com.kash.src;

import java.util.Comparator;
import java.util.List;

/**
 * Interface that provides all sorting functions for all possible representations of a list of Objects (non-primitive
 * types). <br>
 * - {@link List}<{@link Comparable}><br>
 * - Array of < ? extends {@link Comparable}><br>
 * - {@link List}< ? > with external {@link Comparator}<br>
 * - Array of < ? > with external {@link Comparator}<br>
 * 
 * @author Kashyap Bhatt
 * 
 */

public interface Sorter {
    <T extends Comparable<T>> void sort(List<T> list);

    <T extends Comparable<T>> void sort(T[] array);

    <T extends Object> void sort(List<T> list, Comparator<? super T> c);

    <T extends Object> void sort(T[] array, Comparator<? super T> c);
}

这样我就可以测试我所有的排序实现并测试它们。我想将结果与 Java 的排序实现进行比较,所以我也在编写这个接口的实现,它在内部只调用 Java 的排序方法。这就是我遇到问题的地方。

4

3 回答 3

3

Collections#sort预计List您正在传递一个数组。
做:

public static <T> void sort1(T[] array, Comparator<? extends T> c) {
        Collections.sort(Arrays.asList(array), c); // line 11
}
于 2012-09-19T20:32:57.740 回答
3

Collections.sort()不对数组进行排序,而是对Lists.

于 2012-09-19T20:33:11.573 回答
1

Collections 类型中的方法sort(List<T>, Comparator<? super T>)不适用于参数(T[], Comparator<capture#1-of ? extends T>)Main.java /Sorting/src/com/kash/test 第 11 行

您正在通过预期的T[]地方和预期的地方。List<T>Comparator<? extends T>Comparator<? super T>

为什么你认为它不应该给出错误?

于 2012-09-19T20:35:30.740 回答