13

我有一个方法:

public List<Stuff> sortStuff(List<Stuff> toSort) {
    java.util.Collections.sort(toSort);

    return toSort;
}

这会产生一个警告:

Type safety: Unchecked invocation sort(List<Stuff>) of the generic method sort(List<T>) of type Collections.

Eclipse 说修复警告的唯一方法是添加@SuppressWarnings("unchecked")到我的sortStuff方法中。对于 Java 本身内置的东西,这似乎是一种糟糕的方式。

这真的是我唯一的选择吗?为什么或者为什么不?提前致谢!

4

4 回答 4

52

Collections.sort(List<T>)期望T必须实施Comparable<? super T>。似乎Stuff确实实现Comparable但不提供泛型类型参数。

确保声明这一点:

public class Stuff implements Comparable<Stuff>

而不是这个:

public class Stuff implements Comparable
于 2013-03-19T14:16:23.663 回答
6

Do tou use this:

// Bad Code
public class Stuff implements Comparable{

    @Override
    public int compareTo(Object o) {
        // TODO
        return ...
    }

}

or this?

// GoodCode
public class Stuff implements Comparable<Stuff>{

    @Override
    public int compareTo(Stuff o) {
        // TODO
        return ...
    }

}
于 2013-03-19T14:36:48.207 回答
0

您将需要更改方法的返回类型

于 2013-03-19T14:28:23.803 回答
0

对通用集合进行排序

该类中定义了两个排序函数,如下所示:

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

public static <T> void sort(List<T> list, Comparator<? super T> c);

Neither one of these is exactly easy on the eyes and both include the wildcard (?) operator in their definitions. The first version accepts a List only if T extends Comparable directly or a generic instantiation of Comparable which takes T or a superclass as a generic parameter. The second version takes a List and a Comparator instantiated with T or a supertype.

于 2013-03-19T14:31:57.763 回答