Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a custom list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading