3

I have to write a method to sort both Integers and Doubles.

public ArrayList<Number> sortDescending(ArrayList<Number> al){
    Comparator<Number> c=Collections.reverseOrder();
    Collections.sort(al,c);
    return al;
}

public ArrayList<Number> sortAscending(ArrayList<Number> al){
    Collections.sort(al);
    return al;
}

The problem is that in sortAscending, the following error occurs:

Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (ArrayList). The inferred type Number is not a valid substitute for the bounded parameter < T extends Comparable < ? super T>>

2 Answers 2

9

You need to use a generic upper bound of Number intersecting with Comparable<T>:

public <T extends Number & Comparable<T>> ArrayList<T> sortDescending(ArrayList<T> al){
    Comparator<T> c=Collections.reverseOrder();
    Collections.sort(al,c);
    return al;
}

public <T extends Number & Comparable<T>> ArrayList<T> sortAscending(ArrayList<T> al){
    Collections.sort(al);
    return al;
}

All JDK Numbers (eg Float, Integer etc) match this typing.

For the uninitiated, the syntax <T extends A & B> is the way you bound T to both A and B.

FYI, there is no syntax for "or" logic (nor would it make sense if you think about it)

2
  • 2
    FYI: There's no reason to have a return type on either of your methods, as the List is sorted in place.
    – Matt
    Jul 16, 2012 at 15:47
  • 1
    @Matt Rather than "no reason", there are several reasons to have return types: A) To illustrate the implications of typing the method, B) That's what the OP had and C) Returning objects from "non-getter" methods is done when implementing the fluent API pattern
    – Bohemian
    Jul 17, 2012 at 1:01
4

You are getting the error because number does not implement Comparable<Number>. You need to add a generic contstraint so that it extends both number and Comparable. In this case:

public <T extends Number & Comparable<T>> ArrayList<T> sortAscending(ArrayList<T> al){
    Collections.sort(al);
    return al;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.