I was trying to filter specific elements from an Iterator object, and I can remove the false elements via iterator.remove()
method.
Here is my method stub:
private static Iterator<A> process(Iterator<A> iter, Per p) {
while(iter.hasNext()){
A o = iter.next();
if(p.per(o)){
iter.remove();
}
}
return iter;
}
I can remove the un-related elements, but when I look into the java api for Iterator.reomve(), it's saying:
void remove(): Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
I just confused about why it's an optional operation? Is it a warning to let programmer be more careful when using the remove() method? or it has other meanings?
Thanks for you all in advance for help.
And the whole code I was compiling is below for your reference:
package com.test.iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorTest {
public static void main(String[] args) {
final IteratorTest it = new IteratorTest();
List<A> list = new ArrayList<A>(){{
add(it.new A(10));
add(it.new A(11));
add(it.new A(12));
add(it.new A(13));
add(it.new A(16));
}};
Iterator<A> iter = list.iterator();
iter = process(iter, it.new Per());
System.out.println("");
}
private static Iterator<A> process(Iterator<A> iter, Per p) {
while(iter.hasNext()){
A o = iter.next();
if(p.per(o)){
iter.remove();
}
}
return iter;
}
class A{
private String name;
private int age;
public A(int i){
this.age = i;
this.name = i + ",wang";
}
}
class Per{
public boolean per(A a){
if(a.age % 2 == 0){
return true;
}else{
return false;
}
}
}
}
It means that per the contract of the API, the remove()
method is not required to be implemented / available on all implementations. This is because on some implementations, it simply may not make sense - or would be infeasible to implement. A good example would be the iterator returned on a read-only collection - such as the one returned by Collections.unmodifiableCollection()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With