java.lang.Comparable <t>无法转换为T&#34;

时间:2017-12-02 01:10:14

标签: java generics equals doubly-linked-list comparable

public class DoubleLinkedList<T> implements DoubleLinkedListADT<T> {
    //Double linked list node class
    public class DoubleLinkedListNode<T>  {
        T info;
        DoubleLinkedListNode<T> next;
        DoubleLinkedListNode<T> back;

        public DoubleLinkedListNode() {
            info = null;
            next = null;
            back = null;
        }

        public String toString() {
            return info.toString();
        }
    }

    protected int count;                     //number of nodes
    protected DoubleLinkedListNode<T> first; //reference to first node
    protected DoubleLinkedListNode<T> last;  //reference to last node

    public boolean equals(Object o) {
        if(o instanceof DoubleLinkedList) {
            DoubleLinkedList<T> d = (DoubleLinkedList) o;
            if(count != d.count){
              return false;
            }
            else{
                DoubleLinkedListNode<T> curr = first;
                DoubleLinkedListNode<T> curr2 = d.first;
                while(curr != null && curr2 != null){
                    Comparable<T> temp = (Comparable<T>) curr.info;
                    Comparable<T> temp2 = (Comparable<T>) curr2.info;
                    if(temp.compareTo(temp2) >= 0){
                      return false;
                    }
                    curr = curr.next;
                    curr2 = curr2.next;
                }
                return true;
            }
        }
        else
            return false;
    }
}    

问题在于这个if语句,&#34; if(temp.compareTo(temp2)&gt; = 0)&#34;。

错误是&#34;不兼容的类型:java.lang.Comparable无法转换为T&#34;。

我认为问题是当我对类型对象进行类型转换时

1 个答案:

答案 0 :(得分:1)

首先,您必须将DoubleLinkedList的声明更改为

class DoubleLinkedList<T extends Comparable<T>>

因此编译器知道TComparable<T>并且可以确保您提供的任何参数类都将保证具有compareTo()方法。

然后,您不需要临时值,因为T实现了Comparable<T>,您只需直接比较T个实例:

while(curr != null && curr2 != null){
    if(curr.info.compareTo(curr2.info) >= 0){
      return false;
    }
    curr = curr.next;
    curr2 = curr2.next;
}

不确定为什么你认为你需要施展到Comparable<T>。请注意Comparable<T>.compareTo的定义是

int compareTo​(T o);

而不是

int compareTo​(Comparable<T> o)

您评论道:

  

我添加了可扩展Comparable,但它与我的界面相冲突,我不想更改我的界面,因为这是为了作业。

您有冲突,但它介于接口的定义和分配的要求之间。您已将行为添加到列表的equals()方法中,该方法取决于包含的元素之间的排序比较。如果这确实是所需行为的一部分,那么接口类型参数T必须声明为<T implements Comparable<T>>以强制类型安全。考虑在实例化DoubleLinkedList时会发生什么,其中排序比较对于类型参数的对象没有意义,例如

DoubleLInkedList<Map<String,Integer>> list = new DoubleLinkedList<>();

如果您可以仅使用equals()来实现所需的行为,那么您可以省略类型约束。否则,你放弃了泛型设计提供的类型安全性,并且设计被打破了。