2021-11-14Iterator迭代器
生活随笔
收集整理的這篇文章主要介紹了
2021-11-14Iterator迭代器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.Iterator迭代器介紹
集合的遍歷有兩種:迭代器或者增強for循環。為什么不用for循環獲得每個元素呢?因為在list里面有索引,但是在set里面沒有索引。
有索引的時候可以用for循環,但是集合中有的沒有索引,所以用Iterator迭代器進行遍歷
2.迭代器的代碼實現
Demo01Iterator.java
package Iterator;import java.util.ArrayList; import java.util.Collection; import java.util.Iterator;/** java.util.Iterator接口:迭代器(對集合進行遍歷)* Iterator迭代器,是一個接口,我們無法直接使用,需要使用Iterator接口的實現對象,獲取實現類的方式比較特殊* Collection接口中又一個方法,叫iterator(),這個方法返回的就是迭代器的實現類對象* Iterator<E> iterator() 返回在此collection的元素上進行迭代的迭代器** 迭代器的使用步驟(重點):* 1.使用集合中的方法iterator()獲取迭代器的實現類對象,使用Iterator接口接收(多態)* 2.使用Iterator接口中的方法hasNext判斷還有沒有下一個元素* 3.使用Iterator接口中的方法next去除集合中的下一個元素* */ public class Demo01Iterator {public static void main(String[] args) {//1.創建集合對象Collection<String> coll = new ArrayList<>();//2、往集合里面添加元素coll.add("張三");coll.add("李四");coll.add("王五");coll.add("趙六");coll.add("田七");/** 1.使用集合中的方法iterator()獲取迭代器的實現類對象,使用Iterator接口接收(多態)* 注意:* Iterator<E>接口也是有泛型的,迭代器的泛型跟著集合走,集合是什么泛型,迭代器就是什么泛型* *///多態Iterator<String> it = coll.iterator();/** 發現使用迭代器取出集合中元素的代碼,是一個重復的過程* 所以我們可以使用循環優化* 不知道集合中有多少個元素,使用while循環* 循環結束的條件,hasNext方法返回false** */while (it.hasNext()) {System.out.println(it.next());}//張三//李四//王五//趙六//田七// boolean b = it.hasNext(); // System.out.println(b);//true // String next = it.next(); // System.out.println(next);//張三 // // boolean b1 = it.hasNext(); // System.out.println(b1);//true // String next1 = it.next(); // System.out.println(next1);//李四 // // boolean b2 = it.hasNext(); // System.out.println(b2);//true // String next2 = it.next(); // System.out.println(next2);//王五 // // boolean b3 = it.hasNext(); // System.out.println(b3);//true // String next3 = it.next(); // System.out.println(next3);//趙六 // // boolean b4 = it.hasNext(); // System.out.println(b4);//true // String next4 = it.next(); // System.out.println(next4);//田七 // // boolean b5 = it.hasNext(); // System.out.println(b5);//false // String next5 = it.next(); // //System.out.println(next5);//NoSuchElementException} }3.迭代器的原理
4.增強For
Demo02ForEach.java
package Iterator;import java.util.ArrayList; import java.util.Collection;public class Demo02ForEach {public static void main(String[] args) {//1.遍歷數組int[] array = new int[]{1, 2, 3, 4, 5};for (int a : array) {System.out.println(a);}//1//2//3//4//5//2.遍歷集合Collection<String> coll = new ArrayList<>();coll.add("張三");coll.add("李四");coll.add("王五");coll.add("趙六");coll.add("田七");for (String c : coll) {System.out.println(c);}//張三//李四//王五//趙六//田七} } 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的2021-11-14Iterator迭代器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021-11-14Collection
- 下一篇: 2021-11-14泛型