【问题标题】:How to refer to Enclosing class from Inner class?如何从内部类引用封闭类?
【发布时间】:2012-04-21 01:02:38
【问题描述】:

我正在扩展 ArrayList 以创建一个自定义 ArrayList,在迭代它时可以使用普通的 ArrayList 方法对其进行修改。为此,我还创建了一个迭代器。

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

在我的 hasNext() 和 next() 方法中,我需要确保列表没有被修改(可以在任何其他时间修改)。因此,我需要在 synchronized() 块中引用我的封闭类型。

【问题讨论】:

标签: java class arraylist nested synchronized


【解决方案1】:

EnclosingType.this。所以在你的情况下,它会是SynchronizedList.this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    相关资源
    最近更新 更多