简体   繁体   中英

linked list iterator inner class-java

I am writing an iterator inner class that iterates through a list. Besides the remove method, I believe I have implemented all the methods of iterator correctly but I get an error saying "Bound mismatch: The type E is not a valid substitute for the bounded parameter > of the type List.Node". I believe this has to with having Node> implements Iterable at the top of my code but I do not want to change that if unneeded. Any possible suggestions on what I should do?

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() {

        }

    }
}

You should reduce the number of generic types. Because the inner classes know the generic type of their parent class, you should simplify the Node and ListIterator class:

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() {

        }

    }
}

The type parameter N is declared as

N extends Comparable<N>

ie. it has bounds. It must be Comparable to itself.

The type parameter E is declared as

E

ie. it has no bounds. It can be any type, but not necessarily a type that is Comparable to itself.

Therefore, you can't use E where an N is expected. Consider adding the same bounds as N to E .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM