简体   繁体   中英

Java - sorting using Collections.sort()

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>>

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)

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM