这是我的代码
class LinkedUserList implements Iterable{
protected LinkedListElement head = null; /*Stores the first element of the list */
private LinkedListElement tail = null; /*Stores the last element of the list */
public int size = 0; /* Stores the number of items in the list */
//Some methods....
//...
public Iterator iterator() {
return new MyIterator();
}
public class MyIterator implements Iterator {
LinkedListElement current;
public MyIterator(){
current = this.head; //DOSEN'T WORK!!!
}
public boolean hasNext() {
return current.next != null;
}
public User next() {
current = current.next;
return current.data;
}
public void remove() {
throw new UnsupportedOperationException("The following linked list does not support removal of items");
}
}
private class LinkedListElement {
//some methods...
}
}
问题是我有一个称为head的受保护变量,但是当尝试从MyIterator子类访问它时,尽管该变量受到保护,它也无法正常工作。
为什么它不起作用,我该怎么办?
非常感谢!!!
this
始终引用当前对象。所以,内MyIterator
,this
指的是MyIterator
实例,而不是名单。
您需要使用LinkedUserList.this.head
或简单head
地访问head
外部类的成员。请注意,内部类可以访问其外部类的私有成员,因此head
不必如此protected
。可以private
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句