我獲得以下編譯錯誤:Java泛型:通配符捕獲編譯錯誤
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
當我編譯(帶有JDK 1.7.0在Eclipse的Juno)驗證碼:
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 Generics: Wildcard capture misunderstanding
- What is PECS (Producer Extends Consumer Super)?
- 更多閱讀以上:
- 編輯 -
對於挑剔的人誰也想知道我爲什麼要做這樣的傻事。如果你不在乎我爲什麼要這樣做,不要打擾其他人。
爲什麼?
我寫幾種實現方式(例如:快速,插入,堆,混合,介紹,氣泡,...)以下接口:
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排序方法的接口實現。那就是我遇到問題的地方。
謝謝。愚蠢的我。 :)我應該在這個包裝器中調用Arrays.sort()。 – Kashyap