Java generics warnings on java.util.Collections

后端 未结 4 1710
生来不讨喜
生来不讨喜 2021-02-19 23:39

I have a method:

public List sortStuff(List toSort) {
    java.util.Collections.sort(toSort);

    return toSort;
}

T

相关标签:
4条回答
  • 2021-02-20 00:33

    Collections.sort(List<T>) expects that T must implement Comparable<? super T>. It seems like Stuff does implement Comparable but doesn't provide the generic type argument.

    Make sure to declare this:

    public class Stuff implements Comparable<Stuff>
    

    Instead of this:

    public class Stuff implements Comparable
    
    0 讨论(0)
  • 2021-02-20 00:39

    Do tou use this:

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

    or this?

    // GoodCode
    public class Stuff implements Comparable<Stuff>{
    
        @Override
        public int compareTo(Stuff o) {
            // TODO
            return ...
        }
    
    }
    
    0 讨论(0)
  • 2021-02-20 00:40

    Sorting Generic Collections

    There are two sorting functions defined in this class, shown below:

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

    Neither one of these is exactly easy on the eyes and both include the wildcard (?) operator in their definitions. The first version accepts a List only if T extends Comparable directly or a generic instantiation of Comparable which takes T or a superclass as a generic parameter. The second version takes a List and a Comparator instantiated with T or a supertype.

    0 讨论(0)
  • 2021-02-20 00:41

    You will need to change the return type of your method

    0 讨论(0)
提交回复
热议问题