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
联系方式:wuchaodzxx@126.com