Introduction
In this article, we will learn about cursor in the collection framework. If we want to get objects from the collection one by one, we have to use the cursor. Using the cursor, we can retrieve or traverse the object from the collection one by one. There are three cursors in the collection framework-
- Enumeration
- Iterator
- ListIterator
1. Enumeration Cursor
Enumeration is used to retrieve elements from the collection one by one. We can get an enumeration object by using the elements() method.
How to create an enumeration object?
Enumeration e=v.elements();
Here, v is a Vector class object.
Enumeration Methods
There are two methods,
- hasMoreElements() - This method checks whether more elements are present inside the collection or not.
- nextElement() - This method provide next element from collection, if collection have more elements.
Example
import java.util.*;
class abc{
public static void main(String args[]){
Vector v=new Vector();
v.add("Abhishek");
v.add("Harshit");
v.add("Shruti");
v.add("Pranav");
v.add("Arpit");
v.add("Ishika");
//Create enumeration object
Enumeration e=v.elements();
// apply enumeration methods
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
}
}
Output
Enumeration Limitations
- Enumeration is not a universal cursor. It is applicable for legacy classes. Vector class is an example of a legacy class.
- We can not perform the remove operation using enumeration.
2. Iterator Cursor
The iterator cursor is introduced to overcome the limitation of the enumeration cursor. An iterator is used to retrieve elements from the collection one by one. The iterator is a universal cursor which means it is applicable for all collection classes.
How to create an Iterator object?
Iterator itr=list.iterator();
Here, the list is an ArrayList class object.
Iterator Methods
There are three methods,
- hasNext() - This method checks whether more elements are present inside the collection or not.
- next() - This method provides the next element from the collection if the collection has more elements.
- remove() - This method removes the elements from the collection.
Example
import java.util.*;
class abc{
public static void main(String args[]){
ArrayList list=new ArrayList();
list.add("Abhishek");
list.add("Harshit");
list.add("Shruti");
list.add("Pranav");
list.add("Arpit");
list.add("Ishika");
//Create iterator object
Iterator itr=list.iterator();
// apply Iterator methods
while(itr.hasNext()){
String str=String.valueOf(itr.next());
if(str.equals("Abhishek")){
// apply remove method
itr.remove();
}
else{
System.out.println(str);
}
}
// Updated list
System.out.println("List:"+list);
}
} 
Join the conversation! Your thoughts help the community grow.