受到这个问题的启发:如何实现 Iterable我决定制作一个基本的链表实现并实现一个迭代器,以便拥有这样的代码:
MyList<String> myList = new MyList<String>();
myList.add("hello");
myList.add("world");
for(String s : myList) {
System.out.println(s);
}
代码并不难处理,class MyList<T> implements Iterable<T>
用 aprivate static class Node<T>
和 a创建 a private class MyListIterator<T> implements Iterator<T>
,但是在实现我自己的版本时遇到了一个问题Iterator#remove
:
class MyList<T> implements Iterable<T> {
private static class Node<T> {
//basic node implementation...
}
private Node<T> head;
private Node<T> tail;
//constructor, add methods...
private class MyListIterator<T> implements Iterator<T> {
private Node<T> headItr;
private Node<T> prevItr;
public MyListIterator(Node<T> headItr) {
this.headItr = headItr;
}
@Override
public void remove() {
//line below compiles
if (head == headItr) {
//line below compiles
head = head.getNext();
//line below doesn't and gives me the message
//"Type mismatch: cannot convert from another.main.MyList.Node<T> to
//another.main.MyList.Node<T>"
head = headItr.getNext();
//line below doesn't compile, just for testing purposes (it will be deleted)
head = headItr;
}
}
}
}
这个错误信息引起了我的好奇心。我在网上寻找有关此问题的信息,但一无所获(或者我可能不太擅长搜索此类问题)。比较同一类型的两个变量但不能相互分配的原因是什么?
顺便说一句,我知道我可以只查看LinkedList
Java 设计人员的代码并检查它是如何实现的,然后将其复制/粘贴/调整到我自己的实现中,但我更愿意对真正的问题进行解释和理解。
显示我当前MyList
类实现的完整代码:
class MyList<T> implements Iterable<T> {
private static class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
super();
this.data = data;
}
public T getData() {
return data;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}
private Node<T> head;
private Node<T> tail;
private int size;
public MyList() {
head = null;
tail = null;
}
public void add(T data) {
Node<T> node = new Node<T>(data);
if (head == null) {
head = node;
tail = head;
} else {
tail.setNext(node);
tail = node;
}
size++;
}
private class MyListIterator<T> implements Iterator<T> {
private Node<T> headItr;
private Node<T> prevItr;
public MyListIterator(Node<T> headItr) {
this.headItr = headItr;
}
@Override
public boolean hasNext() {
return (headItr.getNext() != null);
}
@Override
public T next() {
T data = headItr.getData();
prevItr = headItr;
if (hasNext()) {
headItr = headItr.getNext();
}
return data;
}
@Override
public void remove() {
if (head == headItr) {
//problem here
head = headItr.getNext();
}
//implementation still under development...
}
}
@Override
public Iterator<T> iterator() {
return new MyListIterator<T>(head);
}
}