Inferred type is not a valid substitute for a Comparable generic type

前端 未结 4 2003
感动是毒
感动是毒 2021-01-11 11:11

Consider the code:

public abstract class Item implements Comparable
{
    protected T item;

    public int compareTo(T o)
    {
        re         


        
4条回答
  •  青春惊慌失措
    2021-01-11 11:46

    Actually more detailed explanation of this error gives your javac itself:

    java: no suitable method found for sort(java.util.ArrayList>)

    method java.util.Collections.sort(java.util.List,java.util.Comparator) is not applicable (cannot instantiate from arguments because actual and formal argument lists differ in length)

    method java.util.Collections.sort(java.util.List) is not applicable (inferred type does not conform to declared bound(s) inferred: MyItem bound(s): java.lang.Comparable>)

    So, the main question is:
    why is method Collections.sort(java.util.List)) not applicable?

    The answer is:
    because in Collections.sort(java.util.List) method declaration there are bounds on parameter T: >.

    In another words, T must implement Comparable interface on it self. For example String class implements such interface: ...implements ... Comparable.

    In your case Item class doesn't implement such interface:

    Item implements Comparable is not same thing as Item implements Comparable>.

    So, for solving this problem, your should change your Item class to this one:

    public abstract class Item implements Comparable>
    {
        protected T item;
    
        public int compareTo(Item o)
        {
            return 0; // this doesn't matter for the time being
        }
    }
    

提交回复
热议问题