Cursor types in java

Cursors of Collection Framework in Java

Cursors of Collection Framework in Java

  1. Cursors of Collection Framework in Java
  2. Iterator Cursors of Collection Framework in Java
  3. ListIterator Cursors of Collection Framework
  4. Enumeration Cursors in Java
  5. Comparison Between Iterator, ListIterator and Enumeration Cursors in Java
Cursors of Collection Framework in Java:

Cursors are mainly used to access the elements of any collection. We have the following three types of cursors in Collection Framework:

Iterator Cursors of Collection Framework in Java

This cursor is used to access the elements in the forward direction only. This cursor can be applied to any Collection Interfaces. While accessing the methods we can also delete the elements. An iterator is an interface and we cannot create an object directly. If we want to create an object for Iterator we have to use the iterator() method.

Creation of Iterator
Syntax : Iterator it = c.iterator();
Here, the iterator() method internally creates and returns an object of a class that implements the Iterator Interface.

Methods of Iterator:
  1. boolean hasNext(): returns true if there is a next element in the array list.
  2. Object next(): returns the next element in the array list.
  3. void remove(): removes an element from an array list.
Sample Program to demonstrate Iterator Cursors in Java
import java.util.*; public class IteratorDemo < public static void main (String[]args) < LinkedList < Integer >ll = new LinkedList < Integer >(); ll.add (10); ll.add (25); ll.add (50); ll.add (20); ll.add (25); ll.add (23); ll.add (60); ll.add (25); ll.add (30); ll.add (40); ll.add (15); ll.add (25); System.out.println (ll); Iterator it = ll.descendingIterator (); while (it.hasNext ()) < System.out.println (it.next ()); >Iterator it1 = ll.descendingIterator (); while (it1.hasNext ()) < Integer e = (Integer) it1.next (); //down casting if (e == 25) < it1.remove (); >> System.out.println (ll); > >

Example to demonstrate Iterator Cursors in Java

ListIterator Cursors of Collection Framework in Java

This cursor is used to access the elements of Collection in both forward and backward directions. This cursor can be applied only for List category Collections. While accessing the methods we can also add, set, delete elements. ListIterator is an interface and we cannot create Object directly. If we want to create an object for ListIterator we have to use ListIterator() method.

Читайте также:  Python create window tkinter

Creation of ListIterator
Syntax : ListIterator it = l.listIterator();
Here, listIterator() method internally creates and returns an object of a class that implements the ListIterator Interface.

Methods of ListIterator:
  1. boolean hasNext(): return true if the given list iterator contains more number of elements during traversing the given list in the forward direction.
  2. Object next(): return the next element in the given list. This method is used to iterate through the list.
  3. boolean hasPrevious(): is used to retrieve and remove the head of the deque.
  4. Object previous(): return the previous element from the list and moves the cursor in a backward position. The above method can be used to iterate the list in a backward direction.
  5. int nextIndex(): return the index of the element which is returned by the next() method.
  6. int previousIndex(): return the index of the given element which is returned by a call to previous. The method may return -1 if and only if the iterator is placed at the beginning of the list.
  7. void remove(): remove the last element from the list which is returned by next() or previous() method.
  8. void set(Object obj): is used to replace the last element which is returned by the next() or previous() along with the given element.
  9. void add(Object obj): is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by the next() method.
Sample Program to demonstrate ListIterator Cursors of Collection Framework in Java
import java.util.LinkedList; import java.util.ListIterator; public class ListIteratorDemo < public static void main (String[]args) < LinkedList < Integer >ll = new LinkedList < Integer >(); ll.add (10); ll.add (25); ll.add (50); ll.add (20); ll.add (25); ll.add (23); ll.add (40); ll.add (15); ll.add (25); System.out.println (ll); ListIterator < Integer >lit = ll.listIterator (); System.out.println ("Elements in Forward Direction"); while (lit.hasNext ()) < System.out.println (lit.next () + " "); >System.out.println ("\n elements in Backward direction"); while (lit.hasPrevious ()) < System.out.println (lit.previous () + " "); >while (lit.hasNext ()) < Object o = lit.next (); Integer e = (Integer) o; if (e == 23) < lit.add (56); >if (e == 15) < lit.set (15000); >if (e == 25) < lit.remove (); >> System.out.println ("\n New List:" + ll); > >

Example to demonstrate ListIterator Cursors of Collection Framework in Java

Enumeration Cursors of Collection Framework in Java

This cursor is used to access the elements of Collection only in a forward direction. This is a legacy cursor and can be applied only for legacy classes like Vector, Stack, Hashtable. Enumeration is also an interface and we cannot create the object directly. If we want to create an object for Enumeration we have to use a legacy method called the elements() method. The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.

Читайте также:  Rabbitmq java basic consume

Creation of Enumeration
Syntax : Enumeration e = v.elements();
Here, the elements() method internally creates and returns an object of a class that implements the Enumeration Interface.

Methods of Enumeration
  1. boolean hasMoreElements(): When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated.
  2. Object nextElement(): This returns the next object in the enumeration as a generic Object reference.
Program to demonstrate Enumeration Cursors of Collection Framework in Java
import java.util.*; public class EnumerationDemo < public static void main(String[] args) < Vectorv = new Vector(); v.add(10); v.add(25); v.add(50); v.add(20); v.add(25); v.add(23); v.add(25); System.out.println(v); Enumeration e = v.elements(); while(e.hasMoreElements()) < System.out.println(e.nextElement()+" "); >> >

Example demonstrate Enumeration Cursors of Collection Framework in Java

Comparison Between Iterator, ListIterator and Enumeration Cursors in Java

Comparison Between Iterator, ListIterator and Enumeration Cursors in Java

In the next article, I am going to discuss Set Collections in Java with examples. Here, in this article, I try to explain Cursors of Collection Framework in Java and I hope you enjoy this Cursors of Collection Framework in Java article.

Источник

Cursors in java

If we want to get objects one by one from the Collection then, we should go for Cursor . There are four types of Cursors available in java:

Note: Spliterator is introduced in java 8 so I’ll discuss about it in some other post when I’ll be brushing up my skills on java 8 feature.

Enumeration

  • We can use Enumeration to get objects one by one from legacy Collection object.
  • We can create Enumeration objects by using elements() method of Vector class.
public Enumeration elements(); // e.g. Enumeration e = v.elements(); // where v is some legacy Collection object 
Methods of Enumeration
public boolean hasMoreElements(); // checks whether more elements are present in the Collection. public Object nextElement(); // Returns the next element 

Implementation Demo:

Vector v = new Vector(); for(int i = 0; i  11; i++) v.addElement(i); > System.out.println(v); Enumeration e = v.elements(); while(e.hasMoreElements()) Integer i = (Integer) e.nextElement(); if(i % 2 == 0) System.out.print(i + " "); > 

Limitations of Enumeration

  1. We can apply Enumeration concept only for legacy classes therefore, Enumeration is not a universal Cursor .
  2. By using Enumeration , we can get only read access but we cannot perform remove operation.

To overcome above limitations, we should go for Iterator .

Iterator

  1. We can apply Iterator concept for any Collection object and hence it is universal Cursor .
  2. By using Iterator , we can perform both read and remove operations.
  3. We can create Iterator object by using iterator() method of Collection interface.
public Iterator iterator(); e.g. Iterator itr = c.iterator(); // where c is any Collection object. 

Methods of Iterator

public boolean hasNext(); public Object next(); public void remove(); 

Note: You can see the methods for any Classes or interface using the command javap java.util.Iterator .

Implementation Demo

List al = new ArrayList(); // To remove warning use Generics for(int i = 0; i  11; i++) al.add(i); Iterator itr = al.iterator(); while(itr.hasNext()) Integer i = (Integer) itr.next(); if(i % 2 != 0) // Remove all the odd numbers from ArrayList al itr.remove(); > System.out.println(al); // [0, 2, 4, 6, 8, 10] > 

Limitations of Iterator

  1. By using Enumeration and Iterator , we can always iterate only in forward direction and we cannot iterate the Collection object in backward direction. These are single direction Cursors.
  2. By using Iterator , we can perform only read and remove operations and we cannot perform replacement and addition of new objects.

To overcome above limitations, we should go for ListIterator .

ListIterator

  1. ListIterator is the child interface of Iterator and hence all methods present in Iterator are available to the ListIterator by default.
  2. By using ListIterator , we can iterate the Collection objects either in forward or backward direction and hence it is bi-directional cursor.
  3. By using ListIterator , we can perform replacement and addition of new objects in addition to read and remove operations.
  4. We can create ListIterator by using listIterator() method of List interface.
public ListIterator listIterator(); // e.g. ListIterator ltr = l.listIterator(); // where l is any List object. 

Methods of ListIterator

ListIterator defines the following 9 methods:

// The below three methods are meant for forward iteration public boolean hasNext(); public Object next(); public int nextIndex(); // The below three methods are meant for backward iteration public boolean hasPrevious(); public Object previous(); public int previousIndex(); // Extra operations public void remove(); public void add(Object o); public void set(Object o); 

Note: You can see the methods for any Classes or interface using the command javap java.util.ListIterator .

Implementation Demo

LinkedList ll = new LinkedList(); ll.add("Mandy8055"); ll.add("David"); ll.add("Nag"); ll.add("Saurabh"); System.out.println(ll); ListIterator ltr = ll.listIterator(); while(ltr.hasNext()) String s = ltr.next().toString(); if(s.equals("Mandy8055")) ltr.remove(); else if(s.equals("Saurabh")) ltr.add("Lipika"); else if(s.equals("Nag")) ltr.set("Shweta"); > System.out.println(ll); // [David, Shweta, Saurabh, Lipika] 

The most powerful Cursor is ListIterator but its limitation is it is applicable only for List interface.

Comparison(gist) between 3 Cursors:

Properties Enumeration Iterator ListIterator
1. where we can apply. Only for legacy classes. Applicable for any Collection classes. Applicable only for List Objects.
2. Is it legacy? Yes NO NO
3. Iteration Direction Forward direction Forward direction Bi-directional i.e. forward and backward.
4. Allowed operations Only read operation Read and remove operation. Read, remove, add and replace operation.
5. Method to get the Cursor Using elements() method of Vector class. Using iterator method of Collection interface. Using ListIterator of List interface.
6. Important Methods 2 Methods 3 methods 9 methods

Internal Implementation of Cursors:

This is one of the most disturbing topic which I came through when I was preparing for my java certification. I was thinking every time we want to define a Cursor on some Collection object, I would create an object like Enumeration e or Iterator itr , etc. but then I realized how can we even think of creating an object for Interface since, Enumeration , Iterator and ListIterator are Interfaces.

Finally, I got the solution of this problem by running the below program.

Vector v = new Vector(); Enumeration e = v.elements(); System.out.println(e.getClass().getName()); Iterator itr = v.iterator(); System.out.println(itr.getClass().getName()); ListIterator ltr = v.listIterator(); System.out.println(ltr.getClass().getName()); 
  • The first print statement showed java.util.Vector$1 . The meaning of $1 is there is an anonymous inner class of Vector class and the object is created for that anonymous inner class.
  • Similarly, the second and third print statement showed java.util.Vector$Itr . and java.util.Vector$ListItr . The meaning of $Itr and $ListItr is there are inner classes Itr and ListItr of Vector class simultaneously and the objects are created for those inner class.

Источник

Оцените статью