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

前端 未结 4 1991
感动是毒
感动是毒 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:30

    You do not need to have the class MyItem generified just to see the effect. The following class is enough to see what happens:

    public class MyItem extends Item {}
    

    Now you have the following call:

    Collections.sort(list);
    

    As morgano stated correctly, the sort method will take a collection that is parameterized with a type T that must be comparable to T. Your MyItem class is extending Item, which results in MyItem being comparable to Strings.

    With a little switch in which class implements the Comparable interface, you will get the expected result:

    public abstract class Item {
        protected T item;
    }
    
    public class MyItem extends Item implements Comparable {
        @Override
        public int compareTo(MyItem o) {
            return item.compareTo(o.item); // just an example
        }
    }
    

    And now the call to Collections.sort(list) will work.

提交回复
热议问题