What Is Iterator In Addition To Listiterator Inward Coffee Plan Alongside Example - Tutorial Code Sample

Iterator inward Java is cipher but a traversing object, made specifically for Collection objects similar List and Set. nosotros convey already aware nearly dissimilar form of traversing methods similar for-loop ,while loop,do-while,for each lop etc,they all are  index based traversing but equally nosotros know Java is purely object oriented language at that spot is ever possible ways of doing things using objects together with therefore Iterator is a means to traverse equally good equally access the information from the collection. Even amongst traversing amongst object nosotros convey Enumeration, Iterator together with ListIterator inward Java which nosotros volition inward this Java Iterator tutorial.


What is Iterator inward Java API:

Java iterator is an interface belongs to collection framework allow us to traverse the collection together with access the information chemical constituent of collection without bothering the user nearly specific implementation of that collection it. Basically List together with laid collection provides the iterator. You tin larn Iterator from ArrayList, LinkedList, together with TreeSet etc. Map implementation such equally HashMap doesn’t render Iterator directory but yous tin larn at that spot keySet or Value Set together with tin iterator through that collection.
Syntax:
It comes within java.util package. equally public interface Iterator and contains iii methods:

boolean hasNext(): this method returns truthful if this Iterator has to a greater extent than chemical constituent to iterate.

Object next(): return the side past times side chemical constituent inward the collection until the hasNext() method render true. Its ever recommended to telephone outcry upward hasNext() method earlier calling next() method to avoid java.util.NoSuchElementException: Hashtable Iterator

remove(): method take away the final chemical constituent render past times the iterator this method exclusively calls in i lawsuit per telephone outcry upward to next().



How to create Iterator inward Java:

 nosotros convey already aware nearly dissimilar form of traversing methods similar  What is Iterator together with ListIterator inward Java Program amongst Example - Tutorial Code SampleEvery collection classes provides an iterator() method that returns an iterator to the outset of the collection. By using this iterator object, nosotros tin access each chemical constituent inward the collection, i chemical constituent at a time. In general, to purpose an iterator to traverse through the contents of a collection follow these steps:

1.  First obtain an iterator to the beginning  of the collection past times calling the collection's iterator( ) 
2.  Set upward a loop that makes a telephone outcry upward to hasNext( ). Have the loop iterate equally long equally hasNext( ) returns true.
3.  Within the loop, obtain each chemical constituent past times calling next( ).


Java Iterator tutorial together with Example


Example of How to purpose Iterator inward Java
Here is consummate code instance of How to purpose Iterator inward Java. This Java programme creates Hashtable, populate it amongst dummy information together with than uses Iterator to traverse Map together with prints cardinal together with value for each Entry. This Java Program uses Generic version of Iterator to ensure type-safety together with avoid casting .


import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Simple Java Program which shows How to purpose Iterator inward Java to loop through all elements
 * of Collection classes similar ArrayList, LinkedList, HashSet or Map implementation like
 * HashMap,TreeMap together with Hashtable.
 */

public class IteratorExample{

    public static void main(String[] args) {
        //Hashtable instance used for Iterator Example inward Java
        Hashtable<Integer, String> stockTable=new Hashtable<Integer,String>();

        //Populating Hashtable instance amongst sample values
        stockTable.put(new Integer(1), "Two");
        stockTable.put(new Integer(2), "One");
        stockTable.put(new Integer(4), "Four");
        stockTable.put(new Integer(3), "Three");

        //Getting Set of keys for Iteration
        Set<Entry<Integer, String>> stockSet = stockTable.entrySet();

        // Using Iterator to loop Map inward Java, hither Map implementation is Hashtable
        Iterator<Entry<Integer, String>> i= stockSet.iterator();
        System.out.println("Iterating over Hashtable inward Java");
       
        //Iterator begins
        while(i.hasNext()){
            Map.Entry<Integer,String> m=i.next();
            int cardinal = m.getKey();
            String value=m.getValue();
            System.out.println("Key :"+key+"  value :"+value);

        }
        System.out.println("Iteration over Hashtable finished");
    }
}

Output:
Iterating over Hashtable inward Java
Key :4  value :Four
Key :3  value :Three
Key :2  value :One
Key :1  value :Two
Iteration over Hashtable finished




Why purpose Iterator when nosotros convey Enumerator:
Both Iterator and Enumerator is used for traversing of collection but Iterator is to a greater extent than enhanced inward damage of extra method remove () it render us for alter the collection which is non available inward enumeration along amongst that it is to a greater extent than secure it doesn’t allow around other thread to alter the collection when around some other thread is iterating the collection together with throws concurrentModificationException. Along amongst this method get upward are besides really convenient inward Iterator which is non major departure but brand purpose of iterator to a greater extent than easy.


What is List Iterator inward Java?
ListIterator in Java is an Iterator which allows user to traverse Collection similar HashSet in both management past times using method previous() and next (). You tin obtain ListIterator from all List implementation including ArrayList together with LinkedList. ListIterator doesn’t continue electrical current index together with its electrical current seat is determined past times telephone outcry upward to next() or previous() based on management of traversing.


Important indicate nearly Iterator inward Java:

1) Iterator inward Java back upward generics together with therefore ever purpose Generic version of Iterator rather than using Iterator amongst raw type.

2) If yous desire to take away objects from Collection than don't purpose for-each loop instead purpose Iterator's remove() method to avoid whatsoever ConcurrentModificationException.

3) Iterating over collection using Iterator is dependent land to ConcurrentModificationException if Collection is modified afterwards Iteration started, but this exclusively happens inward instance of fail-fast Iterators.

4) There are ii types of Iterators inward Java, fail-fast together with fail-safe, banking concern jibe difference betwixt fail-safe together with fail-fast Iterator for to a greater extent than details.

5) List collection type besides supports ListIterator which has add() method to add together elements inward collection patch Iterating. There are around to a greater extent than differences betwixt Iterator together with ListIterator similar bidirectional traversing, which nosotros convey discussed above. Also why ListIterator has add() method is a popular Java Collection Interview question.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Advanced usage of Enum inward Java amongst Example

Komentar

Postingan populer dari blog ini

Common Multi-Threading Mistakes Inwards Coffee - Calling Run() Instead Of Start()

3 Examples Of Parsing Html File Inwards Coffee Using Jsoup

Why You Lot Should Command Visibility Of Shape Too Interface Inward Java