Iterators Used Reading From a File Java

A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream object'south elements one past one. There are three cursors in Java.

  1. Iterator
  2. Enumeration
  3. ListIterator

Note: SplitIterator can also be considered as a cursor equally it is a type of Iterator only.

1. Iterator

Iterators in Java are used in the Collection framework to think elements one by ane. It is a universal iterator as we can apply it to any Collection object. By using Iterator, we can perform both read and remove operations. It is an improved version of Enumeration with the additional functionality of removing an chemical element.

Iterator must exist used whenever we want to enumerate elements in all Collection framework implemented interfaces similar Set up, List, Queue, Deque, and all implemented classes of Map interface. Iterator is the only cursor available for the entire collection framework.
Iterator object can be created by calling iterator() method present in Drove interface.

Syntax:

Iterator itr = c.iterator();

Note: Here "c" is any Collection object. itr is of type Iterator interface and refers to "c".

Methods of Iterator Interface in Java

Iterator interface defines 3 methods as listed beneath:

1. hasNext(): Returns true if the iteration has more elements.

public boolean hasNext();

2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no more than element is nowadays.

public Object adjacent();

3. remove(): Removes the next chemical element in the iteration. This method can exist chosen simply one time per telephone call to adjacent().

public void remove();

Note: remove() method tin throw ii exceptions namely as follows:

  • UnsupportedOperationException : If the remove performance is non supported past this iterator
  • IllegalStateException : If the adjacent method has not yet been called, or the remove method has already been chosen after the final call to the next method.

How does Java Iterator Works Internally?

In this section, nosotros volition endeavor to understand how Java Iterator and its methods work internally. Permit us take the following LinkedList object to empathize this functionality.

List<String> cities = new LinkedList<>();  cities.add("G-one");  cities.add("G-2");  cities.add("G-3");  .  .  .  cities.add("1000-n");

Now, let u.s.a. create an Iterator object on List object every bit shown below:

Iterator<String> citiesIterator = cities.iterator();

The "citiesIteartor" iterator will look like –

Hither Iterator's Cursor is pointing before the commencement element of the List.

Now, nosotros will run the following code snippet.

citiesIterator.hasNext(); citiesIterator.next();

When we run the higher up code snippet, Iterator'due south Cursor points to the kickoff element in the listing equally shown in the in a higher place diagram.

Now, we will run the following code snippet.

citiesIterator.hasNext(); citiesIterator.side by side();

When we run the to a higher place code snippet, Iterator's Cursor points to the second element in the list as shown in the above diagram. Do this process to accomplish the Iterator's Cursor to the end element of the Listing.

Later reading the final element, if nosotros run the below code snippet, information technology returns a "faux" value.

citiesIterator.hasNext();

As Iterator's Cursor points to the after the terminal element of the List, hasNext() method returns a fake value.

Note: After observing all these diagrams, we can say that Java Iterator supports only Forward Direction Iteration as shown in the below diagram. And so it is too known equally Uni-Directional Cursor.

Example:

Java

import java.util.ArrayList;

import java.util.Iterator;

public class Exam {

public static void main(String[] args)

{

ArrayList<Integer> al = new ArrayList<Integer>();

for ( int i = 0 ; i < 10 ; i++)

al.add(i);

System.out.println(al);

Iterator itr = al.iterator();

while (itr.hasNext()) {

int i = (Integer)itr.next();

System.out.print(i + " " );

if (i % 2 != 0 )

itr.remove();

}

System.out.println();

Organization.out.println(al);

}

}

Output

[0, 1, 2, 3, 4, 5, 6, vii, eight, 9] 0 1 2 iii 4 5 6 7 8 9  [0, 2, 4, six, eight]

SplitIterator

Spliterators, similar other Iterators, are for traversing the elements of a source. A source can exist a Drove, an IO channel, or a generator part. It is included in JDK viii for support of efficient parallel traversal(parallel programming) in addition to sequential traversal. Java Spliterator interface is an internal iterator that breaks the stream into smaller parts. These smaller parts tin exist processed in parallel.

Note: In real life programming, we may never need to apply Spliterator directly. Nether normal operations, information technology will behave exactly the same equally Java Iterator.

Advantages of Java Iterator

  • We can use it for any Collection class.
  • It supports both READ and REMOVE operations.
  • Information technology is a Universal Cursor for Drove API.
  • Method names are simple and easy to use them.

Also, there are sure limitations of Iterator which are listed equally follows:

Limitations of Java Iterator

  • In CRUD Operations, it does NOT support CREATE and UPDATE operations.
  • It supports simply Forward direction iteration that is a Uni-Directional Iterator.
  • Compare to Spliterator, it does Not support iterating elements parallel which ways it supports only Sequential iteration.
  • Compare to Spliterator, information technology does Not support better performance to iterate large book of data.

2. Enumeration

It is an interface used to get elements of legacy collections(Vector, Hashtable). Enumeration is the starting time iterator present from JDK 1.0, rests are included in JDK 1.ii with more than functionality. Enumerations are besides used to specify the input streams to a SequenceInputStream. We can create an Enumeration object by calling elements() method of vector course on whatever vector object

// Here "five" is an Vector class object. e is of // type Enumeration interface and refers to "v" Enumeration e =            five.elements();

There are 2 methods in the Enumeration interface namely :

i. public boolean hasMoreElements(): This method tests if this enumeration contains more than elements or not.

ii. public Object nextElement(): This method returns the next chemical element of this enumeration. It throws NoSuchElementException if no more element is nowadays

Coffee

import java.util.Enumeration;

import java.util.Vector;

public course Test

{

public static void main(String[] args)

{

Vector v = new Vector();

for ( int i = 0 ; i < x ; i++)

v.addElement(i);

System.out.println(v);

Enumeration eastward = v.elements();

while (east.hasMoreElements())

{

int i = (Integer)e.nextElement();

System.out.print(i + " " );

}

}

}

Output:

[0, 1, 2, 3, 4, 5, 6, 7, viii, 9] 0 ane 2 3 iv v 6 vii 8 9        

In that location are certain limitations of enumeration which are as follows:

  • Enumeration is for legacy classes(Vector, Hashtable) only. Hence information technology is not a universal iterator.
  • Remove operations can't be performed using Enumeration.
  • Just frontwards direction iterating is possible.

Similarities betwixt Coffee Enumeration and Iterator

  • Both are Java Cursors.
  • Both are used to iterate a Drove of object elements one past one.
  • Both back up READ or Retrieval operation.
  • Both are Uni-directional Java Cursors which ways support only Forward Direction Iteration.

Differences between Java Enumeration and Iterator

The following tabular array describes the differences between Java Enumeration and Iterator:

Enumeration Iterator
Introduced in Java 1.0 Introduced in Java 1.2
Legacy Interface Not Legacy Interface
Information technology is used to iterate only Legacy Collection classes. We tin use it for any Collection form.
It supports only READ operation. Information technology supports both READ and DELETE operations.
It's not Universal Cursor. It is a Universal Cursor.
Lengthy Method names. Simple and like shooting fish in a barrel-to-use method names.

three. ListIterator

Information technology is only applicable for List collection implemented classes like ArrayList, LinkedList, etc. It provides bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator. ListIterator object can be created by calling listIterator() method nowadays in the List interface.

ListIterator ltr = l.listIterator();

Note: Here "50" is any List object, ltr is of type. ListIterator interface and refers to "fifty". ListIterator interface extends the Iterator interface. And so all three methods of Iterator interface are available for ListIterator. In addition, there are six more methods.

1. Forward direction

i.1 hasNext(): Returns true if the iteration has more than elements

public boolean hasNext();

one.2 next(): Same equally side by side() method of Iterator. Returns the next chemical element in the iteration.

public Object adjacent();

1.3 nextIndex(): Returns the adjacent element alphabetize or list size if the list iterator is at the end of the list.

public int nextIndex();

2. Astern direction

2.ane hasPrevious(): Returns truthful if the iteration has more elements while traversing astern.

public boolean hasPrevious();

2.2 previous(): Returns the previous element in the iteration and can throw NoSuchElementException if no more element present.

public Object previous();

2.iii previousIndex(): Returns the previous element index or -1 if the list iterator is at the beginning of the list,

public int previousIndex();

3. Other Methods

three.i remove(): Same as remove() method of Iterator. Removes the adjacent chemical element in the iteration.

public void remove();

3.2 set up(Object obj): Replaces the last element returned by next() or previous() with the specified element.

public void set(Object obj);        

iii.3 add(Object obj): Inserts the specified element into the list at the position before the chemical element that would be returned past next()

public void add(Object obj);

Conspicuously, the three methods that ListIterator inherits from Iterator (hasNext(), adjacent(), and remove()) exercise exactly the same thing in both interfaces. The hasPrevious() and the previous operations are exact analogues of hasNext() and side by side(). The quondam operations refer to the element before the (implicit) cursor, whereas the latter refers to the element after the cursor. The previous operation moves the cursor backward, whereas the side by side moves information technology forward.

ListIterator has no current element; its cursor position always lies betwixt the element that would exist returned by a phone call to previous() and the element that would be returned past a call to next().

ane. set() method tin can throw iv exceptions.

  • UnsupportedOperationException: if the set operation is non supported by this list iterator
  • ClassCastException: If the form of the specified chemical element prevents it from existence added to this list
  • IllegalArgumentException: If some aspect of the specified chemical element prevents it from being added to this list
  • IllegalStateException: If neither adjacent nor previous take been chosen, or remove or add have been chosen after the terminal phone call to next or previous

2. add() method tin throw 3 exceptions.

  • UnsupportedOperationException: If the add method is not supported past this list iterator
  • ClassCastException: If the course of the specified chemical element prevents it from beingness added to this list
  • IllegalArgumentException: If some aspect of this element prevents information technology from beingness added to this listing

Example:

Coffee

import java.util.ArrayList;

import coffee.util.ListIterator;

public class Exam {

public static void main(Cord[] args)

{

ArrayList al = new ArrayList();

for ( int i = 0 ; i < x ; i++)

al.add(i);

System.out.println(al);

ListIterator ltr = al.listIterator();

while (ltr.hasNext()) {

int i = (Integer)ltr.next();

Organisation.out.print(i + " " );

if (i % ii == 0 ) {

i++;

ltr.set(i);

ltr.add together(i);

}

}

System.out.println();

System.out.println(al);

}

}

Output:

[0, i, 2, 3, four, v, 6, 7, 8, 9] 0 1 2 3 iv v 6 vii 8 9  [1, 1, 1, 3, 3, 3, 5, five, v, 7, vii, 7, 9, 9, 9]

Annotation: Similarly, there are sure limitations with ListIterator. It is the most powerful iterator only it is only applicative for List implemented classes, and then information technology is not a universal iterator.

Important Points

  1. Please annotation that initially, any iterator reference will bespeak to the index but before the index of the starting time element in a drove.
  2. We don't create objects of Enumeration, Iterator, ListIterator considering they are interfaces. Nosotros use methods like elements(), iterator(), listIterator() to create objects. These methods have an anonymous Inner Class that extends respective interfaces and return this class object.

Note: The $ symbol in reference class proper noun is a proof that concept of inner classes is used and these grade objects are created.

This can be verified by the below code. For more on inner class refer

Java

import java.util.Enumeration;

import coffee.util.Iterator;

import java.util.ListIterator;

import java.util.Vector;

public class GFG {

public static void main(String[] args)

{

Vector v = new Vector();

Enumeration e = 5.elements();

Iterator itr = five.iterator();

ListIterator ltr = five.listIterator();

System.out.println(e.getClass().getName());

System.out.println(itr.getClass().getName());

Organization.out.println(ltr.getClass().getName());

}

}

Output

java.util.Vector$one java.util.Vector$Itr coffee.util.Vector$ListItr

franklinthemblent.blogspot.com

Source: https://www.geeksforgeeks.org/iterators-in-java/

0 Response to "Iterators Used Reading From a File Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel