Reputation: 28841
Here is my code
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...
}
}
The problem is that I have a protected variable called head, but when trying to access it from a subclass MyIterator, then it does not work, despite the variable being protected.
Why is it not working and what can i do about fixing it????
Many Thanks!!!
Upvotes: 1
Views: 654
Reputation: 691625
this
always refers to the current object. So, inside MyIterator
, this
refers to the MyIterator
instance, not the list.
You need to use LinkedUserList.this.head
, or simply head
, to access the head
member of the outer class. Note that inner classes can access private members of their outer class, so head
doesn't need to be protected
. It can be private
.
Upvotes: 4