Cannot convert from Node<E> to Node<E>?

和自甴很熟 提交于 2019-12-08 14:16:25

You've declared two different generic types: E (for Node) and E extends Comparable<E> (for DoublyLinkedList).

The main issue here is probably MyListIter, which is a non-static inner class and as such automatically inherits DoublyLinkedList's definition of E. Because it inherits the definition of E, you should just be declaring it as

private class MyListIter implements ListIterator<E>

but you've made it MyListIter<E>, which is redefining E to something different than the E that DoublyLinkedList users (implicit E extends Object vs. E extends Comparable<E>).

I think Node should work as-is since it is a nested class (with the static keyword) and doesn't inherit the definition of E from DoublyLinkedList. However, it'd probably make sense here to declare it as a non-static inner class of DoublyLinkedList (private class Node) the same as MyListIter.

Also, you should probably allow E to be a type that is a subtype of some type that implements Comparable by declaring it as E extends Comparable<? super E>.

It looks like you're getting this error because you're redefining E in your Node nested class. Since it's a static nested class, it has no direct relationship to the parent class DoublyLinkedList. It might make more sense to make the class non-static so that E continues to have meaning within it. For example:

private class Node {

Node next = null;
Node prev = null;
E data;

...

EDIT: as ColinD noted, MyListIter should similarly not redeclare E as a type parameter. Changing this like with Node should fix the issue.

ColinD is right (+1).

To understand what's going on, imagine not using the same formal type parameter 3 times, but E for DoublyLinkedList, F for Node and G for MyListIter. Then the error message would say Type mismatch: cannot convert from type DoublyLinkedList.Node<E> to DoublyLinkedList.Node<G>. The solution is the one ColinD suggested. If you want, you can leave Node<F> static, with the fix all instances will have the same actual type parameter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!