您好,登錄后才能下訂單哦!
在Java中,迭代器模式是一種設(shè)計(jì)模式,它使你能夠遍歷一個(gè)聚合對象(如列表或集合)的元素,而無需暴露該對象的內(nèi)部表示。以下是如何在Java中自定義集合并使用迭代器模式實(shí)現(xiàn)的一個(gè)簡單示例:
Iterator
,它包含兩個(gè)主要方法:hasNext()
和next()
。public interface Iterator {
boolean hasNext();
Object next();
}
MyCollection
,它包含一個(gè)用于存儲元素的列表。在這個(gè)例子中,我們將使用一個(gè)簡單的ArrayList
。import java.util.ArrayList;
import java.util.List;
public class MyCollection {
private List<Object> elements;
public MyCollection() {
elements = new ArrayList<>();
}
public void add(Object element) {
elements.add(element);
}
public Iterator iterator() {
return new MyIterator();
}
}
Iterator
接口的MyIterator
類。這個(gè)類需要維護(hù)一個(gè)當(dāng)前元素的索引,并在調(diào)用next()
方法時(shí)返回下一個(gè)元素。public class MyIterator implements Iterator {
private int currentIndex;
private MyCollection collection;
public MyIterator() {
currentIndex = 0;
collection = (MyCollection) this.collection;
}
@Override
public boolean hasNext() {
return currentIndex < collection.elements.size();
}
@Override
public Object next() {
if (!hasNext()) {
throw new RuntimeException("No more elements to iterate");
}
return collection.elements.get(currentIndex++);
}
}
MyCollection
對象,添加一些元素,并使用迭代器遍歷它們。public class Main {
public static void main(String[] args) {
MyCollection collection = new MyCollection();
collection.add("A");
collection.add("B");
collection.add("C");
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
這個(gè)示例展示了如何在Java中自定義集合并使用迭代器模式實(shí)現(xiàn)。當(dāng)然,這只是一個(gè)簡單的例子,實(shí)際應(yīng)用中可能需要根據(jù)具體需求進(jìn)行擴(kuò)展和調(diào)整。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。