我正在扩展 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() block 中引用我的封闭类型。
最佳答案
EnclosingType.this
。因此,在您的情况下,它将是 SynchronizedList.this
。
关于java - 如何从内部类引用封闭类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059951/