Iterable,Iterator和forEach


Iterable

Interface Iterable<T>
方法:
Iterator<T> iterator()

Returns an iterator over a set of elements of type T.

Returns:
    an Iterator.

Iterable接口有一個方法聲明,方法用於獲取迭代器。實現該接口的類表明可以使用foreach來遍歷。實現該接口的類中的iterator()方法必須返回一個迭代器。而迭代器類通常作為內部類來實現,此內部類必須實現Iterator接口。

Iterator

public interface Iterator<E>
An iterator over a collection. 

方法: boolean hasNext()   Returns true if the iteration has more elements. E next()   Returns the next element in the iteration. void remove()   Removes from the underlying collection the last element returned by this iterator (optional operation).

實現該接口的類可以作為迭代器來迭代一個集合內的元素。實現該接口的類常常作為集合類的內部類。

forEach

對集合遍歷。例如

for(String s: arrayList){}

上面的代碼會自動調用arrayList的iterator()方法獲得迭代器iterator對象,故arrayList對象必須實現Iterable接口。迭代器iterator又必須實現Iterator接口,因此迭代器iterator有hasNext()和next()方法,通過這兩個方法就可以實現對arrayList元素的遍歷。

 

以下通過一段代碼對上面三個知識點做一個總結,下面代碼模仿一個ArrayList集合(不過下面的集合不是變長的):

 

import java.util.Iterator;
import java.util.NoSuchElementException;

public class IterableClass<E> implements Iterable<E>{
    private int size=0;//集合包含的元素個數
    private final int capacity;//集合的最大容量
    private Object[] elementData ;
    
    public IterableClass(int size){
        if(size>0){
            capacity = size;
            elementData = new Object [size];
        }else{
            throw new IllegalArgumentException("集合初始化容量參數size傳入非法值: "+
                    size);
        }
        
    }
    public boolean add(E o){
        if(size<capacity){
            elementData[size]=o;
            size++;
            return true;
        }else{
            return false;
        }
    }
    @SuppressWarnings("unchecked")
    public E remove(int index) {
        E oldValue = null;
        if(index>=0 && index<size){
            oldValue = (E) elementData[index];
            int numMoved = size - index - 1;
            if (numMoved > 0)
                System.arraycopy(elementData, index+1, elementData, index,
                                 numMoved);
            elementData[--size] = null; // clear to let GC do its work
            return oldValue;
        }else{
            return null;
        }
    }
    @SuppressWarnings("unchecked")
    public E get(int index){
        if(index>=0&&index<size){
            return (E) elementData[index];
        }else{
            throw new IllegalArgumentException("非法參數index: "+
                    index);
        }
    }
    @Override
    public Iterator<E> iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        @Override
        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        @Override
        public E next() {
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }        
    }
}

測試:
public class Test {
    public static void main(String[] args) {
        //ArrayList a = new ArrayList(1);
        IterableClass<String> array = new IterableClass<String>(10);
        array.add("a");
        array.add("b");
        array.add("c");
        array.add("d");
        System.out.println(array.get(2));
        array.remove(2);
        
        for(String s: array){
            System.out.println(s);
        }
    }

}
輸出:
c
a
b
d

 


免責聲明!

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



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