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

Java 中的迭代器

王林
王林原創
2024-08-30 15:11:37315瀏覽

迭代器是一個接口,用來逐一取得集合中的元素。它位於名為 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
上一篇:Java指令下一篇:Java指令