Вот мой код
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
.