我尝试扩展HashMap
该类以实现自定义remove()
方法,如下所示:
@SuppressWarnings("serial")
private final class EntryHashMap<K, E> extends HashMap<K, E> {
@Override
public E remove(Object key) {
rowKeyMap.remove(key);
colKeyMap.remove(key);
return super.remove(key);
}
}
如果 remove()
直接调用一切都很好,但是当使用迭代器删除条目时,调用的remove()
方法HashMap
而不是上面的覆盖remove()
方法:
public boolean selectiveRemove(Object key) {
boolean result = false;
Iterator<Entry<K, E>> it = entrySet().iterator();
while( it.hasNext() ) {
Entry<K, E> entry = it.next();
K rowKey = entry.getKey();
if( Utils.equals(key, rowKey) ) {
it.remove(); // <<<<< this does not invoke the new `remove()`
result = true;
}
}
return result;
}
查看条目迭代器中的源代码后,我HashMap
看到:
private abstract class HashIterator {
. . .
public boolean hasNext() {
. . .
}
HashMapEntry<K, V> nextEntry() {
. . .
}
public void remove() {
if (lastEntryReturned == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
HashMap.this.remove(lastEntryReturned.key); // <<< Hard coded call to HashMap's remove()
lastEntryReturned = null;
expectedModCount = modCount;
}
}
private final class EntryIterator extends HashIterator
implements Iterator<Entry<K, V>> {
public Entry<K, V> next() { return nextEntry(); }
}
扩展HashMap
类不能访问所有私有字段,所以我不能只修改迭代器,我必须重写很多代码来让我自己的迭代器覆盖那个迭代器。
有没有办法完全覆盖remove()
,以便在每次调用的情况下都会调用它HashMap.remove()
?