Java 泛型 - clearList 实现

Java Generics - clearList implementation

我正在尝试使用泛型编写一个简单的方法。但是我收到编译错误

The method remove() in the type Iterator<T> is not applicable for the arguments (T)"

这是代码。

<T> void empty(List<T> list){       
    Iterator<T> itr = list.iterator();
    while(itr.hasNext()){
        itr.remove(itr.next());//Error here
    }
}

Iterator#remove 没有收到任何参数。从方法中删除参数。

//advance the iterator
itr.next();
//remove the element
itr.remove();

如果您要删除列表中的特定元素,请先与所需条件进行比较,然后删除该元素:

while(itr.hasNext()) {
    T foo = itr.next();
    //do the comparison
    if ( ... ) { // using foo
        itr.remove();
    }
}

Iterator.remove() 不带参数。

public interface Iterator<E>    

remove() 不接受任何参数。

void remove():

从基础集合中移除此迭代器返回的最后一个元素(可选操作)。每次调用 next() 只能调用一次此方法。如果在迭代过程中以除调用此方法以外的任何方式修改基础集合,则迭代器的行为是未指定的。

http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html