Java – using collections Sort()

I have to write a method to sort 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:

Solution

You need to use the general upper limit of the number intersecting the 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 (such as float, integer, etc.) match this type

For inexperienced people, syntax < T extends a & B is the way you bind t to a and B For reference only, there is no grammar of "or" logic (it doesn't make sense if you consider it)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>