java中的iterator迭代器

來源:互聯網
上載者:User

標籤:判斷   style   linked   ring   string   add   oid   group   lin   

Collection的iterator方法返回一個實現了一個Iterator介面的對象

Iterator介面中包含三個方法:

1)E next()

2)boolean hasNext()

3)void remove

具體用法:

Iterator<Integer> integers=collection.iterator();        while(integers.hasNext()){            System.out.print(integers.next()+" ");        }

可以通過調用hasNext()判斷是否達到集合的末尾

調用next()方法返回訪問到的元素

但是也可以通過foreach迴圈實現上述的方法

for(Integer i:collection){            System.out.print(i+" ");        }

 編譯器簡單的將foreach迴圈翻譯為帶有迭代器的迴圈

foreach使用是有條件的,即其必須和實現了Iterable介面的對象一起工作,Collection介面擴充了Iterable介面,所以集合可以使用foreach迴圈

 

Iterator的作用:能夠將遍曆序列與序列底層的結構分開,通過它統一了對容器的訪問

public class AddingGroups {    public static void display(Iterator<String>iterator){        while(iterator.hasNext()){            String s=iterator.next();            System.out.print(s+" "+" ");        }        System.out.println();    }    public static void main(String[] args) {       List<String> list1=new ArrayList<>(Arrays.asList("a","b","c"));       List<String> list2=new LinkedList<>(Arrays.asList("d","e","f"));       Set set1=new HashSet<>(Arrays.asList("g","h","i"));       Set set2=new TreeSet<>(Arrays.asList("j","k","l"));       display(list1.iterator());       display(list2.iterator());       display(set1.iterator());       display(set2.iterator());    }}

通過iterator可以不管集合的類型資訊了

 

java中的iterator迭代器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.