I would like to sort my custom implementation of a list, but it throws a compilation error I don’t understand.
Code:
import java.util.ArrayList;
import java.util.Collections;
public class CustomList<E> extends ArrayList<E>
{
public void sort()
{
Collections.sort(this);
}
}
Error:
CustomList.java:8: error: no suitable method found for sort(CustomList<E>)
Collections.sort(this);
^
method Collections.<T#1>sort(List<T#1>) is not applicable
(inference variable T#1 has incompatible bounds
equality constraints: E
lower bounds: Comparable<? super T#1>)
method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(actual and formal argument lists differ in length))
where E,T#1,T#2 are type-variables:
E extends Object declared in class CustomList
T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
1 error
>Solution :
Try something like:
public class CustomList<E extends Comparable<? super E>> extends ArrayList<E>
{
public void sort()
{
Collections.sort(this);
}
}