tags:

views:

118

answers:

3

I have the following code

public class A extends Iterable<Integer> {
    ...
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {

            A a;

            public boolean hasNext() {
                ...
            }

            public Integer next() {
                ...
            }

            public void remove(){
                ...
            } 
};

I would like to initialize the "a" field in the anonymous class with the instance of A that iterator method was called on. Is it possible?

Thank you.

+7  A: 

You don't need to.

You can call methods on the outer class normally within the inner class.
When you compile it, the compiler will automatically generate a hidden field that contains a reference to the outer class.

To reference this variable yourself, you can write A.this. (A.this is the compiler-generated field and is equivalent to your a field)

SLaks
A: 

Try this:

public class A extends Iterable<Integer> {

  public Iterator<Integer> iterator() {

      final A a = this;

      return new Iterator<Integer>() {
        public boolean hasNext() {
            // here you can use 'a'
        }
      }      
  }

}
rmarimon
Wrong. He wants the outer `this`.
SLaks
The way it is stated is the outer 'this'. If you are in the method iterator() and you ask for 'this' (as I wrote) it refers to the object of which iterator() is a method. So 'a' refers to an object of type 'A'.
rmarimon
+1  A: 

Use :

A a = A.this
Eyal Schneider