简体   繁体   中英

Type mismatch when writing my own iterator

I have written my own LinkedList and since I don't want to iterate manually and always check for null . I thought I should write my own Iterator method to return an iterator.

My problem is, I don't really know how I can link my List and my Iterator together. I think that's the deeper reason for my TypeMismatch problem.

public class SearchList<T extends Comparable<T>> implements List<T> {

    public class Node {
        T obj;
        Node next;
        int occurences;

        public Node() {
            this.obj = null;
            this.next = null;
            this.occurences = 1;
        }
    }

    private Node head;

    //Here are my List methods
}

And here's the iterator method

@Override
public Iterator<T> iterator() {

    Node current = head;

    Iterator<T> iterator = new Iterator<T>() {
        @Override
        public boolean hasNext() {
            return current.next != null;
        }

        @Override
        public T next() {
            return current.next;
        }
    };
    return iterator;
}

Intellij complains about a type mismatch in the overridden next() method of the Iterator.

So how do I implement this the correct way?

current.next is another Node instance (next node) and not the data (of type T )

Change it as

@Override
public T next() {
    T data = current.obj;
    current = current.next;
    return data;
}

Also, your hasNext condition checks current.next != null , and you won't be able to access the last element due to this. This might have to be changed to current != null

This answer assumes you want an Iterable<T> and not Iterable<Node> .

UPDATE:

If you want to iterate over Node , then you must return Iterator<Node>

@Override
public Iterator<Node> iterator() {

    Node current = head;

    Iterator<Node> iterator = new Iterator<>() {
        @Override
        public boolean hasNext() {
            return current!= null;
        }

        @Override
        public T next() {
            Node currentNode = current;
            current = current.next;
            return currentNode;
        }
    };
    return iterator;
}

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