为什么java容器能在for each中遍历(Map除外)
大多數容器的的父類都繼承了iterable接口。接口如下
package java.lang;
public interface Iterable<AnyType>{
Iterator<AnyType> iterator();
}
iterator接口如下:
package java.util;?
public interface Iterator<AnyType>
{?
? ? boolean hasNext();?
? ? AnyType next();?
? ? void remove();?
}
?
在各個容器中重寫了iterator()方法 。在ArrayList中的iterator方法如下
? ? 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
? ? ? ? int expectedModCount = modCount;
? ? ? ? public boolean hasNext() {
? ? ? ? ? ? return cursor != size;
? ? ? ? }
? ? ? ? @SuppressWarnings("unchecked")
? ? ? ? public E next() {
? ? ? ? ? ? checkForComodification();
? ? ? ? ? ? int i = cursor;
? ? ? ? ? ? if (i >= size)
? ? ? ? ? ? ? ? throw new NoSuchElementException();
? ? ? ? ? ? Object[] elementData = ArrayList.this.elementData;
? ? ? ? ? ? if (i >= elementData.length)
? ? ? ? ? ? ? ? throw new ConcurrentModificationException();
? ? ? ? ? ? cursor = i + 1;
? ? ? ? ? ? return (E) elementData[lastRet = i];
? ? ? ? }
? ? ? ? public void remove() {
? ? ? ? ? ? if (lastRet < 0)
? ? ? ? ? ? ? ? throw new IllegalStateException();
? ? ? ? ? ? checkForComodification();
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ArrayList.this.remove(lastRet);
? ? ? ? ? ? ? ? cursor = lastRet;
? ? ? ? ? ? ? ? lastRet = -1;
? ? ? ? ? ? ? ? expectedModCount = modCount;
? ? ? ? ? ? } catch (IndexOutOfBoundsException ex) {
? ? ? ? ? ? ? ? throw new ConcurrentModificationException();
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? final void checkForComodification() {
? ? ? ? ? ? if (modCount != expectedModCount)
? ? ? ? ? ? ? ? throw new ConcurrentModificationException();
? ? ? ? }
? ? }
?
map并沒有繼承collection所以不能foreach遍歷。
?
總結
以上是生活随笔為你收集整理的为什么java容器能在for each中遍历(Map除外)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: String,char,数组,列表 相互
- 下一篇: java内部类的特点