iterator取集合元素

1,完整代碼

//建立兩個arraylist對象
        Collection al = new ArrayList(); //al1添加元素
        al.add("name1"); al.add("name4"); al.add("name3"); Iterator it=al.iterator(); while(it.hasNext()) { System.out.println(it.next()); }

for循環的實現

 

for(Iterator it=al.iterator();it.hasNext();)
        {
            System.out.println(it.next());
        }

 

for()的好處:更節約內存java

Iterator定義在了循環內部,在循環結束後,it就被釋放了,數據結構

而在While中it定義在了循環外面,循環結束後對象依然存在,可是卻沒什麼用處,就形成了內存的浪費this

 

2,什麼是迭代器?

其實就是集合的取出方式。spa

【通俗的講:取一個在就判斷一下集合中還有沒有元素,有就取出,沒有就結束】code

3,迭代器(Iterator)的方法?

next();對象

hasNext();blog

remove();內存

4,關鍵代碼

Iterator it=al.iterator();
        while(it.hasNext())
        {
            System.out.println(it.next());
        }

5,迭代器與集合的關係?

迭代器用於取出集合中的元素,各類集合的底層數據結構並不相同,因此存取方式是不一樣的,每一個集合都具有取出的操做,可是集合的取出比較複雜,不止一個動做,就將取出這個動做封裝成了一個對象rem

定義在內部的緣由:get

迭代器操做的是集合內部的元素,定義在類的內部更加方便

若是建立在外部,還須要建立集合對象

6,iterator實現源代碼【爲了防變代碼的觀看,我把代碼反覆到了自定義的.java文件中,致使的報錯(忽略就好)】

Iterator方法的最初定義是在AbstractList這個類中,他的方法實現很簡單就是return了一個Itr對象,

Itr是什麼呢?

在上圖中能夠看到,它是定義在AbstractList這個類裏面的內部類

在他的內部定義了咱們常常使用的hasNext(),Next(),remove()

而後在Iterator()裏面返回了Itr對象

7,下面是Itr的具體實現源碼 

 private class Itr implements Iterator<E>
    {
    
        int cursor = 0;    
        int lastRet = -1;
        int expectedModCount = modCount;
    
        public boolean hasNext()
        {
            return cursor != size();
        }

        public E next() 
        {
            checkForComodification();
            try 
            {
                E next = get(cursor);
                lastRet = cursor++;
                return next;
            } 
            catch (IndexOutOfBoundsException e)
            {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }
    
        public void remove() {
            if (lastRet == -1)
            throw new IllegalStateException();
                checkForComodification();
    
            try {
            AbstractList.this.remove(lastRet);
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
            expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
            }
        }
    
        final void checkForComodification() 
        {
            if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        }
    }
相關文章
相關標籤/搜索