Cursors in Java and difference between them?

Cursors in Java and difference between them?

Cursors in Java and difference between them?

Cursors in Java and difference between them?
  • If you want to get object one by one from the collection then we should go for the cursor.
  • There are three types of cursors available in Java.
    1. Enumeration
    2. Iterator
    3. ListIterator

Enumeration

  • We can use the enumeration to get objects one by one from legacy collection object.
  • We can create enumeration object by using elements() method of vector class.
    • Public Enumeration elements(); .
//Print even number 

package com.java4us;

import java.util.Enumeration;
import java.util.Vector;

public class Test {
    public static void main(String[] args) {
        Vector vector = new Vector();
        for (int i = 0; i < 10; i++) {
            vector.addElement(i);
        }
        System.out.println(vector);
        Enumeration enumeration = vector.elements();
        while (enumeration.hasMoreElements()) {
            Integer i = (Integer) enumeration.nextElement();
            if (i % 2 == 0) {
                System.out.println(i);
            }
        }
    }
}

Limitations of Enumeration

  • We can enumeration concept only for legacy classes and it’s 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 Iterator.

Leave a Reply

Your email address will not be published. Required fields are marked *

*