gpt4 book ai didi

java - 如何创建E类型的Java列表扩展Comparable<? super E>

转载 作者:行者123 更新时间:2023-12-01 12:28:13 24 4
gpt4 key购买 nike

我正在尝试在 Rosettacode.org 上实现用 java 编写的快速排序方法。

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

最佳答案

这里有很多问题。

首先,为什么你将 main 方法声明为 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绑定(bind)到 Comparable 的对象,它将接受任何符合该边界的列表。

关于java - 如何创建E类型的Java列表扩展Comparable<? super E>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com