受到这个问题的启发:如何实现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>
,其中包含一个 private static class Node<T>
和一个 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);
}
}