我收到以下编译错误:
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) {
}
}
我已阅读以下内容,但并不太了解。有什么帮助吗?
- Java 泛型:通配符捕获误解
- 什么是PECS(Producer Extends Consumer Super)?
- 从上面的线程中阅读更多内容:
- 编辑 -
对于那些想知道我为什么做这么愚蠢的事情的挑剔的人。如果你不在乎我为什么要这样做,那就别打扰其他人了。
为什么?
我正在编写以下接口的几个实现(例如 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 的排序方法。这就是我遇到问题的地方。