有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java泛型警告。util。收藏

我有一个方法:

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) 个答案

  1. # 1 楼答案

    你用这个吗

    // Bad Code
    public class Stuff implements Comparable{
    
        @Override
        public int compareTo(Object o) {
            // TODO
            return ...
        }
    
    }
    

    还是这个

    // GoodCode
    public class Stuff implements Comparable<Stuff>{
    
        @Override
        public int compareTo(Stuff o) {
            // TODO
            return ...
        }
    
    }
    
  2. # 2 楼答案

    ^{}期望T必须实现Comparable<? super T>。看起来Stuff确实实现了Comparable,但没有提供泛型类型参数

    请务必声明:

    public class Stuff implements Comparable<Stuff>
    

    而不是这个:

    public class Stuff implements Comparable
    
  3. # 3 楼答案

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

  4. # 4 楼答案

    Sorting Generic Collections

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

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

    这两个选项都不容易被人看到,而且都包含通配符(?)运算符的定义。第一个版本仅在T直接扩展Comparable或Comparable的泛型实例化(以T或超类作为泛型参数)时才接受列表。第二个版本采用一个列表和一个比较器,并用T或超类型实例化