Home > Blockchain >  Sorting a custom list
Sorting a custom list

Time:07-20

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

CodePudding user response:

Try something like:

public class CustomList<E extends Comparable<? super E>> extends ArrayList<E>
{
    public void sort()
    {
        Collections.sort(this);
    }
}

CodePudding user response:

If you take a look at the documentation: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html#sort(java.util.List)

Sort expects the generic type E to be a subtype of Comparable<E>, if you don't want to constrain your generic type, you'll either need to supply a comparator capable of comparing two Es with each other or you'll have to come up with a method of sorting two objects you know nothing about... (i.e. why they need that constraint)

You could use object id, but that's not a very meaningful order

  • Related