【问题标题】:Java generics warnings on java.util.Collectionsjava.util.Collections 上的 Java 泛型警告
【发布时间】:2013-03-08 06:26:56
【问题描述】:

我有一个方法:

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 本身内置的东西,这似乎是一种糟糕的方式。

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

【问题讨论】:

  • 这是产生错误的实际代码吗?查看“Stuff”的代码可能会有所帮助。

标签: java generics collections


【解决方案1】:

Collections.sort(List&lt;T&gt;) 期望 T 必须实现 Comparable&lt;? super T&gt;Stuff 似乎实现了 Comparable,但没有提供泛型类型参数。

请务必声明:

public class Stuff implements Comparable<Stuff>

而不是这个:

public class Stuff implements Comparable

【讨论】:

  • 这非常适合我。我正在实现 Comparator 并将其更改为 Comparator (例如)以匹配类的比较函数的参数。
【解决方案2】:

你用这个吗:

// 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 ...
    }

}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案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 的通用实例化时才接受 List ,它将 T 或超类作为通用参数。第二个版本采用一个 List 和一个用 T 或超类型实例化的 Comparator。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-27
        • 1970-01-01
        • 2013-12-30
        • 2013-05-01
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多