簡體   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