扩展HashMap以实现自定义remove()

时间:2014-03-18 08:35:14

标签: java android iterator override class-extensions

我尝试扩展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()的{​​{1}}方法而不是上面的覆盖{{} 1}}方法:

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()的每种情况下调用它?

0 个答案:

没有答案