Java Iterator的remove()方法

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

    Iterator 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 docLists = Lists.newArrayList(docList);**
    Iterator iterator = docLists.iterator();
    while (iterator.hasNext()) {
      IndexDoc indexDoc = iterator.next();
      if (!GeoUtils.isValidLat(indexDoc.lat)||!GeoUtils.isValidLon(indexDoc.lon)) {
        iterator.remove();
      }
    }

你可能感兴趣的:(java)