I am trying to implement the Quicksort method written in java on Rosettacode.org.
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Java
However, I do not know how to add elements to a LinkedList of type E in order to use the method.
public static <E extends Comparable<? super E>> void main(String[] args) {
List<E> list = new LinkedList<E>();
list.add(1);
}
I get the following error when I try to compile:
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
There are tons of issues here.
First, why are you declaring your main method as static<E extends Comparable<? super E>>
static<E extends Comparable<? super E>>
.
Secondly, you have bounded the list
to a generic type E
but have not specified what E
is. Thus, to add an int
into a list that has no specific type will cause a conversion issue by the compiler. Also, an int
is a primitive type, it doesn't follow, even when it's autoboxed to java.lang.Integer
, it doesn't satisfy the constraint since E
is not specific/specified.
I hope this helps.
Update:
Based on the link you provided, this is how you will to use the quickSort()
function.
List<Integer> intList = new ArrayList<>(); //If using JDK 7 and higher.
OR
List<Integer> intList = new ArrayList<Integer>(); //If using JDK 6 and JDK 5.
Now...
//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);
Since E
is bounded to an object that is Comparable
, it will accept any list that conforms to that bounding.
In order to add Integer ,You should change
List<E> list = new LinkedList<E>();
to
List<Integer> list = new LinkedList<Integer>();
The reason why you are getting error is due to the fact that when you declared List<E>
then all you can add into list is Element of type E
and Integer is not E
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.