Heim > Java > javaLernprogramm > Hauptteil

Iterator in Java

王林
Freigeben: 2024-08-30 15:11:37
Original
349 Leute haben es durchsucht

An Iterator is an interface that is used to fetch elements one by one in a collection. It is available in a Java package called Java. util package. The collection API implements the iterator() method, and hence data can be retrieved from interfaces like Map, List, Queue, Deque, and Set, which are all implemented from the collection framework. As the name suggests, an iterator in Java iterates through a collection of objects.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Iterator<E> iterator()
Nach dem Login kopieren

Below the iterator is the name of an object created by calling iterator() method of collection interface. “collection” is the collection object’s name.

Iterator iter = collection.iterator();
Nach dem Login kopieren

Methods of Iterator in Java

Iterators have 4 methods in Java that are used to traverse through collections and retrieve the required information. They are as follows:

  • hasNext(): This is a method that returns boolean true if the iteration has a next element present and boolean false if there is no element present next.
  • next (): This method returns the element value present in the coming iteration. Suppose no elements are returned in the next iteration, then a “NoSuchElementException” is thrown.
  • remove(): This method removes the present element returned by the iterator from the collection. In case this method is called previous to the next() method, it throws “IllegalStateException.”
  • forEachRemaining(): This method executes all the remaining elements in the collection until they have been processed or until an exception is thrown. Also, this is a method newly introduced by the Oracle Corporation in their Java SE 8 release.

Example of Iterator in Java

Below is the example of Iterator in Java:

Code:

import java.io.*;
import java.util.*;
public class IteratorExample {
public static void main(String[] args)
{
ArrayList<String> val = new ArrayList<String>();
val.add("Iteration started");
val.add("Printing iteration1");
val.add("Printing iteration2");
val.add("Printing iteration3");
val.add("End of iteration");
// Iterates through the list
Iterator iter = val.iterator();
System.out.println("The values of iteration are as follows: ");
while (iter.hasNext())
System.out.println(iter.next() + " ");
System.out.println();
}
}
Nach dem Login kopieren

Output:

Iterator in Java

Iterator methods throw exceptions

In a list of elements, an iterator can fetch information only on the existing elements. Therefore, it will crash or throw an exception if tried to access an element that is not present in the next iteration. Here we shall get to know the different kinds of exceptions we get while implementing the iterator methods.

1. next() method

While iterating through a set of elements and fetching them by this method.

  • NoSuchElementException: This occurs if the next() tries to retrieve an element that does not exist in the present list. Hence always a hasNext() has to be used before calling next().

2. remove() method

There are 2 kinds of exceptions that can occur here:

  • IllegalStateException: If the remove() method is called before the next() method, then this exception is thrown. This is because the method attempts to remove an element that is not yet specified by the next() method and hence fails. To resolve this exception, next() must be called to refer to the first item and then remove() can be called to remove the same from the list.
  • UnsupportedOperationException: This exception is usually thrown when modifying a list object by adding or removing an operation that does not support modification. For example, when an array is tried to convert to a list by Arrays.asList throws this exception. This is because the List object will have a fixed size as the wrapper creates it from ArrayList, and hence modification will not be allowed. To resolve this issue, convert the Arrays.asList to ArrayList or LinkedList object before performing any operations like add/remove on the same.

Syntax:

//ArrayList is created from the list having fixed size
list = new ArrayList<String>(list);
Iterator<String> iter = list.iterator();
while(iter.hasNext()){
if( iter.next().equals("First iteration") ){
iter.remove();
}
}
Nach dem Login kopieren

Methods of ListIterator

These methods allow the iterator to traverse in both directions of the collection object. Following are some of them:

  • add(): This method inserts the object value given and is returned when the next() method is called.
  • hasNext(): This method is the same as the one mentioned in iterator types, which returns Boolean true/false depending on the next element having a value or not.
  • hasPrevious(): This method is opposite to hasNext() and returns Boolean true if the list has a previous element and vice versa.
  • next(): This method retrieves the next element from the given list.
  • previous(): This method retrieves the previous element from the list.
  • remove(): This deletes the present element from the list. When this method is called either before the next() or previous() function, it throws “IllegalStateException”.

Example for ListIterator

Below is an example in ArrayList for ListIterator.

Code:

import java.util.*;
public class IteratorExample {
public static void main(String args[]) {
// Creating an array list
ArrayList array = new ArrayList();
// add elements to the array list
array.add("First element");
array.add("Second element");
array.add("Third element");
array.add("Fourth element");
array.add("Fifth element");
array.add("Sixth element");
// Displaying elements of an array
System.out.println("Printing input of the array: ");
Iterator iter = array.iterator();
while(iter.hasNext()) {
Object value = iter.next();
System.out.println(value + " ");
}
System.out.println();
// To update the elements of iteration
ListIterator listiter = array.listIterator();
while(listiter.hasNext()) {
Object value = listiter.next();
listiter.set(value + "+");
}
System.out.print("Updated array elements are as follows: ");
iter = array.iterator();
while(iter.hasNext()) {
Object value = iter.next();
System.out.print(value + " ");
}
System.out.println("\n");
// To display the contents in backward direction
System.out.println("Printing elements in backward direction: ");
while(listiter.hasPrevious()) {
Object value = listiter.previous();
System.out.print(value + " ");
}
System.out.println();
}
}
Nach dem Login kopieren

Output:

Iterator in Java

Advantages of Iterators in Java

Below are the advantages of Iterators:

  1. It supports all classes under the Collection interface.
  2. The methods of an iterator are quite simple and easy to understand and implement.
  3. Elements of a Collection can be easily modified (add/remove) using Iterators.
  4. Accessing elements through Iterators will not lead to run-time exceptions.
  5. Data handling is efficient.
  6. It can iterate over various variables concurrently by holding each variable’s state of iteration separately.

Limitations of Iterators in Java

Below are the limitations of Iterators:

  1. Java iterator can iterate only in one direction, i.e. forward direction.
  2. It cannot be used to iterate between two different data structures concurrently.
  3. It cannot be used to backtrace an element.
  4. It does not allow modification of the structure of the element being iterated as it stores its position.
  5. It might be inefficient in certain cases were traversing through the elements directly is more efficient.

Conclusion

Iterators are the most commonly used method to retrieve elements from the collection interface. It is called Universal Java Cursor as it is applicable across all the Collection classes.

Recommended Article

This is a guide to Iterator in Java. Here we discuss methods and examples of Iterator in Java along with its Limitations and Advantages. You can also go through our other suggested articles to learn more –

  1. Overriding in Java
  2. Iterators in C#
  3. Java Collection Interview Questions
  4. Java Iterate Map

Das obige ist der detaillierte Inhalt vonIterator in Java. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!