一、概述
Java Iterator是一種遍歷容器內元素的介面,可以遍歷ArrayList、LinkedList、HashSet、TreeSet、HashMap等容器內的元素。使用Iterator的好處是可以在遍歷時不必關心容器內元素保存的具體順序,而且可以在遍歷過程中修改容器內所保存的元素。
二、Iterator介面的定義
Iterator是Java Collection Framework的一部分,它定義了一個迭代器,用於依次訪問集合中的元素。它的核心方法包括:
- hasNext():檢查迭代器中是否還有下一個元素。
- next():返回下一個元素。
- remove():從迭代器當前指向的位置刪除元素。
三、Iterator使用實例
1. ArrayList迭代器遍歷
下面的代碼使用Iterator遍歷ArrayList,並刪除數組中的指定元素。
ArrayList list = new ArrayList();
Iterator iter = list.iterator();
while (iter.hasNext()) {
String item = iter.next();
if (item.equals("element")) {
iter.remove();
}
}
2. HashMap迭代器遍歷
下面的代碼使用Iterator遍歷HashMap,並輸出Map中的鍵值對。
HashMap map = new HashMap();
Iterator<Map.Entry> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = iter.next();
System.out.println(entry.getKey() + " = " + entry.getValue());
}
3. 自定義類迭代器
下面的代碼展示如何自定義一個迭代器,用於遍歷自定義的MyCollection類中的元素。
public class MyCollection implements Iterable{
private String[] elements = {"a", "b", "c"};
public Iterator iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator {
private int currentIndex = 0;
public boolean hasNext() {
return currentIndex < elements.length && elements[currentIndex] != null;
}
public String next() {
return elements[currentIndex++];
}
public void remove() {
elements[currentIndex] = null;
}
}
public static void main(String[] args) {
MyCollection collection = new MyCollection();
Iterator iter = collection.iterator();
while (iter.hasNext()) {
String item = iter.next();
System.out.println(item);
}
}
}
四、總結
Iterator是Java語言中常用的一個介面,它可以方便地遍歷容器中的元素,並且可以在遍歷過程中動態地修改容器元素。在開發中,使用Iterator可以極大地提高程序的效率和穩定性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/158419.html
微信掃一掃
支付寶掃一掃