What are cursors in java?
- If we want to retrieve objects one by one from the collection then we should go for Cursor. There are 3 types of cursors available in java.
1) Enumeration
2) Iterator
3) ListIterator
Enumeration:
- We can use enumeration to get objects one by one from the Legacy collection object.
- Enumeration is an Interface
- We can create enumeration objects by using elements() method of vector class. [Learn about vector class]
//public enumeration elements() -- method available in vector class
//Enumeration e= v.elements();
//public boolean hasMoreElements() -- method available in Enumeration interface
//public object nextElement() -- method available in Enumeration interface
//Enumeration e= v.elements();
//public boolean hasMoreElements() -- method available in Enumeration interface
//public object nextElement() -- method available in Enumeration interface
Demo program on Enumeration:
public class CursorsDemo {
public static void main(String[] args) {
Vector v = new Vector();
for (int i = 0; i < 10; i++) {
v.addElement(i);
}
System.out.println(v); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Enumeration e = v.elements();
while (e.hasMoreElements()) {
Integer i = (Integer) e.nextElement();
if ((i % 2) != 0)
System.out.println(i); //[1 3 5 7 9]
}
System.out.println(v);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] }
}
Output:
cursors in java |
Limitations of Enumeration:
- We can apply enumeration concept only for legacy classes and it is not a universal cursor
- By using enumeration we can get only read access and we can't perform remove operation
To overcome above limitations we should go for Iterator .
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.