Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

java - How to refer to Enclosing class from Inner class?

I am extending ArrayList to create a custom ArrayList that can be modified using normal ArrayList methods while iterating over it. For this I am also creating an Iterator.

public class SynchronizedList<E> extends ArrayList<E>
{
    // Fields here

    //Constructors and methods here

public class SynchronizedListIterator<E> implements Iterator<E>
{
    public int index;
    private E current;

    public boolean hasNext()
    {
        synchronized (/* reference to enclosing List object */) {
                    //code goes here
        }
        return false;
    }

    //more methods here
}
}

During my hasNext() and next() methods, I need to make sure the list is not modified (it can be modified at any other time). Hence I need to refer to my enclosing type in my synchronized() block.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EnclosingType.this. So in your case, it would be SynchronizedList.this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...