Inner static class inside inner class cannot be converted

我是研究僧i 提交于 2019-12-03 12:45:01

This is the problem:

class MyList<T> implements Iterable<T> {
    private class MyListIterator<T> implements Iterator<T> {
        ...
    }
}

(It doesn't help that in your cut down version you've made MyList non-generic.)

At that point there are two different T type variables - the one in the nested class and the one in the outer class. You don't need Node to be generic - you just need:

class MyList<T> implements Iterable<T> {
    private class MyListIterator implements Iterator<T> {
        ...
    }
}

Now there's only one T - the one in the outer class. It's not like you want the list iterator to have a different T from the one declared in the enclosing instance, so you don't want it to be generic.

To put it another way: try making MyListIterator generic in a type parameter with a different name, and then it'll be clearer what's going wrong, as the two names will be distinguishable in the error message. It's effectively:

Type mismatch: cannot convert from another.main.MyList.Node<TOuter> to
another.main.MyList.Node<TInner>

(or vice versa).

The iterator should be declared as

private class MyListIterator implements Iterator<T>

and not as

private class MyListIterator<T> implements Iterator<T>

By declaring it as MyListIterator, its generic type T is not the same T as the T from its enclosing class.

Remove the type parameter from the declaration of MyListIterator:

private class MyListIterator implements Iterator<T>

and the call in iterator()

public Iterator<T> iterator() {
    return new MyListIterator(head);
}

In your current version the T of MyListIterator isn't the same T as the one in MyList.

The other three are right: you need to change
private class MyListIterator<T> implements Iterator<T>
to
private class MyListIterator implements Iterator<T>
but once you do that, you will also need to change your iterator() method:

public Iterator<T> iterator() {
    return new MyListIterator(head); //was 'return new MyListIterator<T>();'
}

Or else you will get another error. Once you make the second change, then it should work.

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