iterator迭代器
阿新 • • 發佈:2020-07-02
Iterator迭代器
因為各個集合的存取方式不同,所以出現了迭代器,是Collection集合元素的通用獲取方式。
使用
hasNext()如果仍有元素可以疊戴,返回true
next()返回迭代的下一個元素
步驟
- 使用Collection中方法iterator()獲取迭代器的實現類物件,使用Iterator介面接受(多型)
- 使用hasNext()判斷
- 使用next()取出
用while或用for迴圈都可以
程式碼:
public class Main { Collection<Integer> c; public Main() { c = new ArrayList<>(); c.add(1); c.add(2); c.add(3); } public void output1(){ System.out.println("while輸出"); Iterator<Integer> it = c.iterator(); while (it.hasNext()){ System.out.println(it.next()); } } public void output2(){ System.out.println("for輸出"); for(Iterator<Integer>it = c.iterator();it.hasNext();){ System.out.println(it.next()); } } public static void main(String[] args) { Main m = new Main(); m.output1(); m.output2(); } }
實現原理:
c.iterator():獲取迭代器的實現類物件,並且把指標指向集合的-1索引
增強for迴圈
for(集合/陣列的資料型別 變數名:陣列名/集合名){
sout(變數名);
}