Java Collection集合遍歷運(yùn)行代碼實(shí)例
Iterator : 迭代器,集合的專用遍歷方式
Iterator <E> iterator() : 返回此集合中元素的迭代器,通過集合的iterator()方法得到
迭代器是通過集合的iterator()方法得到的,所以我們說(shuō)它是依賴于集合而存在的
Iterator中的常用方法
E next() : 返回迭代中的下一個(gè)元素
boolean hasNext() : 如果迭代具有更多元素,則返回true
代碼如下
public class CollectionDemo_01 { public static void main(String[] args) { //創(chuàng)建集合對(duì)象 Collection<String> c = new ArrayList<String>(); //添加元素 c.add('hello'); c.add('world'); c.add('java'); //Iterator <E> iterator() : 返回此集合中元素的迭代器,通過集合的iterator()方法得到 Iterator<String> it = c.iterator(); /* 閱讀源碼可以知道,iterator方法,返回了一個(gè)實(shí)現(xiàn)Iterator<E>接口的具體實(shí)現(xiàn)類Itr所創(chuàng)建的對(duì)象 public Iterator<E> iterator() {return new Itr(); } private class Itr implements Iterator<E> {} */ //使用while循環(huán)遍歷集合 while (it.hasNext()){ String s = it.next(); System.out.println(s); }/* 運(yùn)行結(jié)果:helloworldjava */ }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java源碼解析之接口List2. Java xml數(shù)據(jù)格式返回實(shí)現(xiàn)操作3. python讀取中文路徑時(shí)出錯(cuò)(2種解決方案)4. XML入門精解之結(jié)構(gòu)與語(yǔ)法5. Python加載數(shù)據(jù)的5種不同方式(收藏)6. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼7. Python用K-means聚類算法進(jìn)行客戶分群的實(shí)現(xiàn)8. layui Ajax請(qǐng)求給下拉框賦值的實(shí)例9. python編寫五子棋游戲10. python mysql 字段與關(guān)鍵字沖突的解決方式
