Home > Software engineering >  use compareTo on more specific Comparables in Java
use compareTo on more specific Comparables in Java

Time:08-16

I would like to have a more specific Comparable interface so that I can type return parameters better. The interface currently looks like this:

public interface SpecialComparable<T extends SpecialComparable<T>> extends Comparable<T> {
}

Now when I try to sort a list of these more specific Comparables as shown below, I get an error because b is of type 'SpecialComparable' not of type 'T'.

public class UserClass {
    public <T extends SpecialComparable<T>> UserClass(List<SpecialComparable<T>> comparables) {
        Collections.sort(comparables, (a, b) -> a.compareTo(b));
    }
}

To solve this problem, I can implement a Self method as shown below. This would solve my problem, but it looks very ugly. I would be happy if someone could find a nicer solution to the problem.

public interface SpecialComparable<T extends SpecialComparable<T>> extends Comparable<T> {
    T self();
}

public class UserClass {
    public <T extends SpecialComparable<T>> UserClass(List<SpecialComparable<T>> comparables) {
        Collections.sort(comparables, (a, b) -> a.compareTo(b.self()));
    }
}

CodePudding user response:

Isn't your problem just here?

public <T extends specialComparable<T>> userClass(List<specialComparable<T>> comparables) {

You have a List<specialComparable<specialComparable<?>>>. That double nesting is presumably not the intention.

Your signature should just be

public <T extends specialComparable<T>> userClass(List<T> comparables) {

FWIW, this interface seems useless since it adds no methods to the regular Comparable. The method is also fairly redundant. You can simply call this on any list of Comparables.

listOfComparables.sort(Comparator.naturalOrder());
  • Related