【问题标题】:linked list iterator inner class-java链表迭代器内部类-java
【发布时间】:2014-10-15 15:15:07
【问题描述】:

我正在编写一个遍历列表的迭代器内部类。除了 remove 方法之外,我相信我已经正确实现了迭代器的所有方法,但是我收到一条错误消息“绑定不匹配:类型 E 不是 List.Node 类型的有界参数>的有效替代品”。我相信这与让 Node> 在我的代码顶部实现 Iterable 相关,但如果不需要,我不想更改它。关于我应该做什么的任何可能的建议?

public class List<T extends Comparable<L>> implements Iterable<L> {

    private class Node<N extends Comparable<N>> {
        private N data;
        private Node<N> next;
    }
    protected Node<L> head;


    public Iterator<L> iterator() {

        return new ListIterator<L>();

    }

    public class ListIterator<E extends Comparable<E>> implements Iterator<E> {

        private Node<E> N = (Node<E>) head; //"Bound mismatch: The type E is not a valid substitute for the bounded parameter <D extends Comparable<D>> of the type List<T>.Node<D>"

        public boolean hasNext() {
            return (N.next != null);
        }

        public E next() {
            if (!hasNext())
                throw new NoSuchElementException();
            else {
                N = N.next;
                return N.data;
            }
        }

        public void remove() {

        }

    }
}

【问题讨论】:

    标签: java linked-list iterator inner-classes


    【解决方案1】:

    您应该减少泛型类型的数量。因为内部类知道其父类的泛型类型,所以应该简化 Node 和 ListIterator 类:

    public class List<L extends Comparable<L>> implements Iterable<L> {
        private class Node {
            private L data;
            private Node next;
        }
        protected Node head;
    
        public Iterator<L> iterator() {
    
            return new ListIterator();
    
        }
    
        public class ListIterator implements Iterator<L> {
    
            private Node N = head;
    
            public boolean hasNext() {
                return (N.next != null);
            }
    
            public L next() {
                if (!hasNext())
                    throw new NoSuchElementException();
                else {
                    N = N.next;
                    return N.data;
                }
            }
    
            public void remove() {
    
            }
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      类型参数N声明为

      N extends Comparable<N>
      

      即。它有界限。它本身必须是Comparable

      类型参数E声明为

      E
      

      即。它没有界限。它可以是任何类型,但不一定是 Comparable 本身的类型。

      因此,您不能在需要 N 的地方使用 E。考虑将与N 相同的边界添加到E

      【讨论】:

      • 嗯,那我可以让 E 扩展 N 吗?
      • @Kracie 你必须让NE 的范围内可用。
      • 我该怎么做?我不认为 N​​ 作为内部类的私人/公共事务可以看到,无论如何,我认为
      • @Kracie 不要让你的生活变得困难。只需为E 声明与N 相同的边界即可。
      • @Kracie No. Read about generic type bounds here. 按其界限,N 被视为Comparable&lt;N&gt;。现在,将E 设为Comparable&lt;E&gt;。它将具有相同(且兼容)的界限。现在可以在需要N 的地方使用它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2015-07-03
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 2021-02-27
      相关资源
      最近更新 更多