简体   繁体   English

编写自己的迭代器时类型不匹配

[英]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 . 我已经编写了自己的LinkedList并且由于我不想手动进行迭代并且总是检查null I thought I should write my own Iterator method to return an iterator. 我以为我应该编写自己的Iterator方法来返回迭代器。

My problem is, I don't really know how I can link my List and my Iterator together. 我的问题是,我真的不知道如何将List和Iterator链接在一起。 I think that's the deeper reason for my TypeMismatch problem. 我认为这是我的TypeMismatch问题的更深层原因。

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. Intellij抱怨迭代器的重写next()方法中的类型不匹配。

So how do I implement this the correct way? 那么我该如何正确实施呢?

current.next is another Node instance (next node) and not the data (of type T ) current.next是另一个Node实例(下一个节点),而不是数据(类型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. 另外,您的hasNext条件将检查current.next != null ,因此您将无法访问最后一个元素。 This might have to be changed to current != null 这可能必须更改为current != null

This answer assumes you want an Iterable<T> and not Iterable<Node> . 此答案假定您需要Iterable<T>而不是Iterable<Node>

UPDATE: 更新:

If you want to iterate over Node , then you must return Iterator<Node> 如果要遍历Node ,则必须返回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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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