[英]declaring Iterator<? extends E & Comparable<? super E>> iterator in java
[英]How to create Java List of Type E extends Comparable<? super E>
我試圖實現在Rosettacode.org上用Java編寫的Quicksort方法。
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Java
但是,我不知道如何將元素添加到類型E的LinkedList中以使用該方法。
public static <E extends Comparable<? super E>> void main(String[] args) {
List<E> list = new LinkedList<E>();
list.add(1);
}
嘗試編譯時出現以下錯誤:
QuickSort.java:12: error: no suitable method found for add(int) list.add(1);
^
method List.add(int,E) is not applicable
(actual and formal argument lists differ in length)
method List.add(E) is not applicable
(actual argument int cannot be converted to E by method invocation conversion)
method Collection.add(E) is not applicable
(actual argument int cannot be converted to E by method invocation conversion) where E is a type-variable:
E extends Comparable<? super E> declared in method <E>main(String[]) 1 error make: *** [c] Error 1
這里有很多問題。
首先,為什么要聲明主要方法為static<E extends Comparable<? super E>>
static<E extends Comparable<? super E>>
。
其次,您已將list
限制為通用類型E
但未指定E
是什么。 因此,將int
添加到沒有特定類型的列表中將導致編譯器發生轉換問題。 另外, int
是原始類型,即使自動裝箱到java.lang.Integer
,它也不會遵循,因為E
不是特定的/指定的,所以它不滿足約束。
我希望這有幫助。
更新:
根據您提供的鏈接,這就是使用quickSort()
函數的方式。
List<Integer> intList = new ArrayList<>(); //If using JDK 7 and higher.
要么
List<Integer> intList = new ArrayList<Integer>(); //If using JDK 6 and JDK 5.
現在...
//Add all your items in the list.
intList.add(1);
intList.add(50);
intList.add(10);
intList.add(8);
intList.add(-24);
//...etc.
//Sort,
intList = quickSort(intList);
由於E
綁定到Comparable
的對象,所以它將接受符合該限制的任何列表。
為了添加Integer,您應該更改
List<E> list = new LinkedList<E>();
至
List<Integer> list = new LinkedList<Integer>();
出現錯誤的原因是由於以下事實:聲明List<E>
您可以添加到列表中的所有元素都是E
類型的元素,而Integer不是E
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.