سؤال

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!!!

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top