Java Collection Framework- Universal Cursor - Iterator in Java- Explained in detail

Published: 01 July 2024
on channel: Learn Java
204
7

You can learn Java with me as the Java Programming language is being made easily. It would take a period of minimum three months and maximum 6 months to master Java. I would recommend you to watch all my videos to crack any software interviews that would require Java Programming language as a primary skill.

Iterator:-
==========
1. It was introduced in JDK1.2 Version.
2. It is a non-legacy cursor.
3. It is applicable for all the implementation for Collection interfaces such as List, Queue and Set
4. You can't instantiate the interface(Iterator)
5. It is a universal cursor.

Steps to achieve Iterator:-
=====================
1. Create an Iterator reference

public Iterator iterator()
ArrayList animals=new ArrayList();
Iterator itr=animals.iterator();

There are 3 important methods in the Java Iterators:-

1. public boolean hasNext():-
=======================

Please be informed that when you invoke hasNext() method on the iterator reference variable, it will return true or false. True will be returned when at least one object is available with respect to the cursor. And, false will be returned when there are no Objects available.

2. public Object next():-
===================
Please be informed that when you invoke next() method on the iterator reference variable, it will do 2 operations

1. It will retrieve the object and will be returned.
2. The cursor will be moved to the next place holder.

Note:-
Please be informed that when you invoke the next() method when hasNext() method invocation has returned false, you will get the below error
java.util.NoSuchElementException

3. public void remove():-
====================

Please be informed that when you want to remove an element from the collection object you can use remove() method.
This will remove the respective collection object.
System.out.println(itr.remove());//This is not possible for void type

Disadvantages:-
=============
It is used only to retrieve or remove elements
It is not used to insert or set an element.
In order to overcome this disadvantages, we will use ListIterator


On this page of the site you can watch the video online Java Collection Framework- Universal Cursor - Iterator in Java- Explained in detail with a duration of hours minute second in good quality, which was uploaded by the user Learn Java 01 July 2024, share the link with friends and acquaintances, this video has already been watched 204 times on youtube and it was liked by 7 viewers. Enjoy your viewing!