【发布时间】:2013-06-30 11:20:41
【问题描述】:
受到这个问题的启发:How to implements 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);
}
}
【问题讨论】:
标签: java generics static inner-classes