[英]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.