0
class UnfairContainer<T> implements Comparable<UnfairContainer>
{    
    private ArrayList<T> array = new ArrayList<T>();

    public void sort()
    {
        Collections.sort(array);
    }

    public int compareTo(UnfairContainer o)
    {

    }
}

所以我有实现可比较的类,但是当我尝试创建调用 Collections.sort() 的排序方法时,它给了我一个错误,说我不能用 ArrayList 调用集合排序。任何人都可以帮忙吗?并帮助我使用 compareTo 方法,我被困在如何比较我的 ArrayList 中的每个元素

4

1 回答 1

1

The problem is that the list is not guaranteed to be sort-able. This is because with your current setup, T could be anything- including a class that does not implement Comparable and hence cannot be sorted by Collections. The type signature of Collections.sort() reflects this:

public static <T extends Comparable<? super T>> void sort(List<T> list);

To fix this, you need to put an upper bound on T to ensure that it is sort-able:

class UnfairContainer<T extends Comparable<T> > 
        implements Comparable<UnfairContainer<T> >
{

...

The T extends Comparable<T> means that T must be a class that implements Comparable. This lets Collections know that the ArrayList can be sorted, and everything works.

For more information, please refer to the java trail on bounded wildcards in generics

于 2013-04-25T03:24:18.663 回答