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()的好處:更節約內存

Iterator定義在了循環內部,在循環結束后,it就被釋放了,

而在While中it定義在了循環外面,循環結束后對象依然存在,但是卻沒什么用處,就造成了內存的浪費

 

2,什么是迭代器?

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

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

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

next();

hasNext();

remove();

4,關鍵代碼

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

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

迭代器用於取出集合中的元素,各種集合的底層數據結構並不相同,所以存取方式是不同的,每個集合都具備取出的操作,但是集合的取出比較復雜,不止一個動作,就將取出這個動作封裝成了一個對象

定義在內部的原因:

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

如果創建在外部,還需要創建集合對象

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();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM