Iterators are used to traverse through the collection element. Its applicable for all collection classes.
Example :
import java.util.Iterator;
import java.util.ArrayList;
public class CursorTest {
public void iteratorTest(){
ArrayList<Integer> ar=new ArrayList<Integer>();
for(int i=0;i<10;i++){
ar.add(i);
}
System.out.println(ar);
Iterator<Integer> it=ar.iterator();
while (it.hasNext()) {
Integer intg=(Integer)it.next();
if (itg % 3==0) {
System.out.println(itg);
}else{
it.remove();
}
}
System.out.println(ar);
}
}
Supported methods :
.hasnext()-Checks if there is any element present in the collection. Return type is boolean .
.next() -Returns the next element in the collection. Return type is object .
.remove()- remove the element from the collection. Does not return anything (void) .