java迭代器基礎(chǔ)知識(shí)點(diǎn)總結(jié)
在學(xué)習(xí)集合的時(shí)候,我們經(jīng)常會(huì)說(shuō)把集合里的元素進(jìn)行遍歷,實(shí)際上這個(gè)過(guò)程有一個(gè)專門的名稱,叫做迭代。迭代器就是對(duì)這種遍歷進(jìn)行操作的工具,好處是能夠使內(nèi)部程序的細(xì)節(jié)得到保密。下面我們就java迭代器的概念、作用進(jìn)行具體的分析,會(huì)結(jié)合一些元素、接口的知識(shí)點(diǎn),最后帶來(lái)使用迭代器的實(shí)例。
1.概念是提供一種方法對(duì)一個(gè)容器對(duì)象中的各個(gè)元素進(jìn)行訪問,而又不暴露該對(duì)象容器的內(nèi)部細(xì)節(jié)。
2.作用java中提供了很多種集合,它們?cè)诖鎯?chǔ)元素時(shí),采用的存儲(chǔ)方式不同。所以當(dāng)我們要取出這些集合中的元素時(shí),可以通過(guò)一種通用的獲取方式來(lái)完成。
Collection集合元素的通用獲取方式: 在取元素之前先要判斷集合中有沒有元素,如果有,就把這個(gè)元素取出來(lái);繼續(xù)再判斷,如果還有就再取出來(lái)。一直到把集合中的所有元素全部取出。這種取出方式專業(yè)術(shù)語(yǔ)稱為迭代。
集合中把這種取元素的方式描述在Iterator接口中。
3.實(shí)例迭代器是java定義的一個(gè)接口,在java.util.Iterator包下。該接口有四大方法,便于實(shí)現(xiàn)了該接口的集合類進(jìn)行訪問操作。
public interface Iterator<E>{E next();boolean hasNextO;void remove0;default void forEachRemaining(Consumer<? super E> action);}
實(shí)例擴(kuò)展:
public class Demo { public static void main(String[] args) { ActualContainer container = new ActualContainer(); for(int i = 5 ; i < 20 ; i++){ container.add(i); } Iterator iterator = container.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } }}/** * 迭代器接口,包含有常用的迭代器方法 */interface Iterator{ public boolean hasNext(); public Object next();}/** * 容器接口:包含有獲取迭代器的方法 */interface Container{ public Iterator iterator();}/** * 具體實(shí)現(xiàn)類 * @author jiaoyuyu * */class ActualContainer implements Container{ private List<Object> list = new ArrayList<>(); public void add(Object obj){ this.list.add(obj); } public void remove(Object obj){ this.list.remove(obj); } public Object get(int index){ if(index <= (this.list.size() - 1)){ return this.list.get(index); } return null; } public Iterator iterator() { return new ActualIterator(); } private class ActualIterator implements Iterator{ private int pointer = 0; public boolean hasNext() { return this.pointer < list.size() ? true : false; } public Object next() { if(this.pointer < list.size()){ Object obj = list.get(pointer); pointer++; return obj; } return null; } }}
到此這篇關(guān)于java迭代器基礎(chǔ)知識(shí)點(diǎn)總結(jié)的文章就介紹到這了,更多相關(guān)java迭代器的基本概念內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML實(shí)體注入深入理解2. XML入門的常見問題(三)3. WMLScript腳本程序設(shè)計(jì)第1/9頁(yè)4. Xpath語(yǔ)法格式總結(jié)5. XML 非法字符(轉(zhuǎn)義字符)6. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂代碼7. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)8. 不要在HTML中濫用div9. 利用CSS3新特性創(chuàng)建透明邊框三角10. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera
