1

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.

1
  • 3
    That should be A implements Iterable. Commented Apr 25, 2010 at 17:36

3 Answers 3

10

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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'
        }
      }      
  }

}

2 Comments

Wrong. He wants the outer this.
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'.
1

Use :

A a = A.this

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.