内部类问题的一般用法

Ank*_*wal 1 java generics

我没有发布整个代码.我有这个:

public class LinkedList2<T extends Comparable<T>> implements Iterable<T> {

    private Node<T> head;
    private Node<T> tail;
    private int numOfElem;

    private class Node<T> {

        Node<T> next;
        T data;

        Node(Node<T> next, T data) {
            this.next = next;
            this.data = data;
        }
    }

    private class LinkedList2Iterator<T> implements Iterator<T> {
            private int count = LinkedList2.this.numOfElem;
            private Node<T> current = LinkedList2.this.head;
    }
}       
Run Code Online (Sandbox Code Playgroud)

javac -Xlint LinkedList2.java我得到这个错误:

LinkedList2.java:134: incompatible types
found   : LinkedList2<T>.Node<T>
required: LinkedList2<T>.Node<T>
        private Node<T> current = LinkedList2.this.head;
                                              ^
1 error
Run Code Online (Sandbox Code Playgroud)

你能帮我吗?

rge*_*man 5

定义内部类时LinkedList2Iterator,您已使用另一个<T>泛型类型参数使其成为通用类.这与外类<T>不匹配.<T>LinkedList2

private class LinkedList2Iterator<T> implements Iterator<T> {
Run Code Online (Sandbox Code Playgroud)

你不需要在<T>这里声明另一个,只需使用<T>外部类,它仍在范围内:

private class LinkedList2Iterator implements Iterator<T> {
Run Code Online (Sandbox Code Playgroud)