2013-03-19 100 views
5

我有一个方法:Java泛型警告

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内置内容的不好方法。

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

+11

你的'void'方法返回一个'List'? – Reimeus 2013-03-19 14:15:16

+2

这么多人很伤心,所以很多人评论一个错误,这显然是由于把问题写到SO而不是回答真正的问题所引起的。 – Sulthan 2013-03-19 14:19:35

+0

当然,但它可能表明这实际上并不是真正的代码运行并产生错误,因此清理它会有所帮助。 – NilsH 2013-03-19 14:20:36

回答

25

Collections.sort(List<T>)预计T必须执行Comparable<? super T>。看起来好像Stuff确实实现了Comparable,但不提供通用类型参数。

确保申报这样的:相反

public class Stuff implements Comparable<Stuff> 

这个:

public class Stuff implements Comparable 
+2

那会是一个错误,不是吗? – 2013-03-19 14:17:29

0

你需要改变你的方法的返回类型

0

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

3

不要土特产品使用:

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

} 
+0

很快看到,如何实现泛型可比。 – 2016-03-02 13:25:59