繁体   English   中英

java.util.Collections上的Java泛型警告

[英]Java generics warnings on java.util.Collections

我有一个方法:

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说修复警告的唯一方法是在我的sortStuff方法中添加@SuppressWarnings("unchecked") 对于Java本身内置的东西来说,这似乎是一种糟糕的方式。

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

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

请务必声明:

public class Stuff implements Comparable<Stuff>

而不是这个:

public class Stuff implements Comparable

请使用这个:

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

}

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

排序通用集合

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM