日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

为什么java容器能在for each中遍历(Map除外)

發布時間:2024/2/28 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 为什么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除外)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。