Java Iterator的remove()方法

来源:互联网 发布:久其软件 亦庄 编辑:程序博客网 时间:2024/06/07 03:34

今天用Iterator.remove()方法删除数据时,抛出java.lang.UnsupportedOperationException异常,代码如下:

    Iterator<IndexDoc> iterator = docLists.iterator();    while (iterator.hasNext()) {      IndexDoc indexDoc = iterator.next();      if (!GeoUtils.isValidLat(indexDoc.lat)||!GeoUtils.isValidLon(indexDoc.lon)) {        iterator.remove();      }    }

API中有说明,如果这个iterator不支持remove操作,会抛出异常。

Throws:UnsupportedOperationException - if the remove operation is not supported by this iterator

而我使用的是CopyOnWriteArrayList,它对应的COWIterator是不支持remove的。

static final class COWIterator<E> implements ListIterator<E> {    /**    * Not supported. Always throws UnsupportedOperationException.    * @throws UnsupportedOperationException always; {@code remove}    *         is not supported by this iterator.     */    public void remove() {        throw new UnsupportedOperationException();    }}

解决办法:
重新转化为可以支持Iterator.remove()的容器。

**List<IndexDoc> docLists = Lists.newArrayList(docList);**    Iterator<IndexDoc> iterator = docLists.iterator();    while (iterator.hasNext()) {      IndexDoc indexDoc = iterator.next();      if (!GeoUtils.isValidLat(indexDoc.lat)||!GeoUtils.isValidLon(indexDoc.lon)) {        iterator.remove();      }    }
阅读全文
0 0