Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop ,while loop,do-while,for each lop etc,they all are index based traversing but as we know Java is purely object oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection. Even with traversing with object we have Enumeration, Iterator and ListIterator in Java which we will in this Java Iterator tutorial.
What is Iterator in Java API
Java iterator is an interface belongs to collection framework allow us to traverse the collection and access the data element of collection without bothering the user about specific implementation of that collection it. Basically List and set collection provides the iterator. You can get Iterator from ArrayList, LinkedList, and TreeSet etc. Map implementation such as HashMap doesn’t provide Iterator directory but you can get there keySet or Value Set and can iterator through that collection.
Syntax:
It comes inside java.util package. as public interface Iterator and contains three methods:
boolean hasNext(): this method returns true if this Itrerator has more element to iterate.
Object next(): return the next element in the collection until the hasNext() method return true. Its always recommended to call hasNext() method before calling next() method to avoid java.util.NoSuchElementException: Hashtable Iterator
remove(): method remove the last element return by the iterator this method only calls once per call to next().
How to create Iterator in Java: इटेरटर जावा कैसे बनाते हैं ?
Every collection classes provides an iterator() method that returns an iterator to the beginning of the collection. By using this iterator object, we can access each element in the collection, one element at a time. In general, to use an iterator to traverse through the contents of a collection follow these steps:
1. First obtain an iterator to the beginning of the collection by calling the collection's iterator( )
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
No comments:
Post a Comment