首页  >  文章  >  Java  >  Java 中的迭代器

Java 中的迭代器

王林
王林原创
2024-08-30 15:11:37363浏览

迭代器是一个接口,用于逐个获取集合中的元素。它位于名为 Java 的 Java 包中。实用程序包。集合 API 实现了 iterator() 方法,因此可以从 Map、List、Queue、Deque 和 Set 等接口检索数据,这些接口都是集合框架实现的。顾名思义,Java 中的迭代器会迭代对象的集合。

语法:

开始您的免费软件开发课程

网络开发、编程语言、软件测试及其他

Iterator<E> iterator()

迭代器下面是调用集合接口的 iterator() 方法创建的对象的名称。 “collection”是集合对象的名称。

Iterator iter = collection.iterator();

Java 中迭代器的方法

Java 中的迭代器有 4 个方法,用于遍历集合并检索所需的信息。它们如下:

  • hasNext(): 如果迭代存在下一个元素,则此方法返回布尔值 true;如果下一个元素不存在,则返回布尔值 false。
  • next (): 此方法返回下一次迭代中存在的元素值。假设下一次迭代没有返回任何元素,则会抛出“NoSuchElementException”。
  • remove(): 此方法从集合中删除迭代器返回的当前元素。如果在 next() 方法之前调用此方法,则会抛出“IllegalStateException”。
  • forEachRemaining(): 此方法执行集合中的所有剩余元素,直到它们被处理或抛出异常。另外,这是 Oracle Corporation 在其 Java SE 8 版本中新引入的方法。

Java 迭代器示例

下面是Java中Iterator的例子:

代码:

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();
}
}

输出:

Java 中的迭代器

迭代器方法抛出异常

在元素列表中,迭代器只能获取现有元素的信息。因此,如果尝试访问下一次迭代中不存在的元素,它将崩溃或引发异常。在这里我们将了解在实现迭代器方法时遇到的不同类型的异常。

1. next() 方法

迭代一组元素并通过此方法获取它们时。

  • NoSuchElementException: 如果 next() 尝试检索当前列表中不存在的元素,则会发生这种情况。因此,在调用 next() 之前始终必须使用 hasNext()。

2.删除()方法

这里可能发生两种异常:

  • IllegalStateException: 如果在 next() 方法之前调用了remove() 方法,则会抛出此异常。这是因为该方法尝试删除 next() 方法尚未指定的元素,因此失败。要解决此异常,必须调用 next() 来引用第一项,然后调用 remove() 将其从列表中删除。
  • UnsupportedOperationException: 当通过添加或删除不支持修改的操作来修改列表对象时,通常会抛出此异常。例如,当尝试通过 Arrays.asList 将数组转换为列表时,会引发此异常。这是因为 List 对象将具有固定大小,因为包装器从 ArrayList 创建它,因此不允许修改。要解决此问题,请先将 Arrays.asList 转换为 ArrayList 或 LinkedList 对象,然后再执行添加/删除等任何操作。

语法:

//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();
}
}

ListIterator 的方法

这些方法允许迭代器在集合对象的两个方向上进行遍历。以下是其中一些:

  • 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();
}
}

Output:

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

以上是Java 中的迭代器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn