首先上圖
?
源碼解析?
打開Collection
接口源碼,能夠看到Collection
接口是繼承了Iterable
接口。
public interface Collection<E> extends Iterable<E> {
? ? /**
? ? ?* ......
? ? ?*/
}
?
?以下是Iterable
接口源碼及注釋
/**
?* Implementing this interface allows an object to be the target of the "for-each loop" statement.
?* 實現這個接口允許一個對象成為for-each循環語句的目標
?*/
public interface Iterable<T> {
?? ?// 返回一個內部元素為T類型的迭代器(JDK1.5只有這個接口)
?? ?Iterator<T> iterator();
?? ?
?? ?// 遍歷內部元素,action意思為動作,指可以對每個元素進行操作(JDK1.8添加)
? ? default void forEach(Consumer<? super T> action) {
? ? ? ? Objects.requireNonNull(action);
? ? ? ? for (T t : this) {
? ? ? ? ? ? action.accept(t);
? ? ? ? }
? ? }
?? ?
?? ?// 創建并返回一個可分割迭代器(JDK1.8添加),分割的迭代器主要是提供可以并行遍歷元素的迭代器,可以適應現在cpu多核的能力,加快速度。
?? ?//(劃重點:并行遍歷元素 并行!)
?? ?default Spliterator<T> spliterator() {
?? ? ? ?return Spliterators.spliteratorUnknownSize(iterator(), 0);
?? ?}
}
?
Iterable接口定義了三個方法,其中兩個提供了默認實現,只有iterator()是要求實現類必須實現的方法。
那么當某個類實現了Iterable接口就可以使用foreach進行迭代。同時Iterable中又封裝了Iterator接口,那么這個類也可以使用Iterator迭代器。
因而有三種方式可以迭代Iterable實現類的對象:
1、for-each循環
List<String> list = new ArrayList><();
list.add("AAA");
list.add("BBB");
list.add("CCC");
for( String element : list ){
? ? System.out.println( element.toString() );
}
?
2、獲取Iterable
實現類對象的迭代器(Iterator)
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
? ? String element = iterator.next();
? ? System.out.println( element );
}
?
3、調用Iterable
的forEach()
方法
list.forEach( (element) -> {
? ? System.out.println( element );
});
?
?Iterator
通過上面我們可以看到,在iterable中我們有一個方法iterator可以返回一個Iterator的類。這個類的作用就是實現迭代。下面我們來看一下這個類的方法以及繼承體系。
雖然在架構層級中并未包含,Iterator
接口(迭代器)也是集合大家庭中的一員。Iterator主要是為了方便遍歷集合中的所有元素(相當于是定義了遍歷元素的范式)。
iterator源碼
public interface Iterator<E> {
?? ?// 是否有下一個元素
?? ?boolean hasNext();?
?? ?
?? ?// 獲取下一個元素
?? ?E next(); ??
?? ?
?? ?// 移除元素
?? ?default void remove() {
?? ??? ?throw new UnsupportedOperationException("remove");
?? ?}
?? ? ? ?
?? ?// 對剩下的所有元素進行處理,action則為處理的動作,意為要怎么處理
?? ?default void forEachRemaining(Consumer<? super E> action) {
?? ??? ?Objects.requireNonNull(action);
?? ??? ?while (hasNext())
?? ? ? ?action.accept(next());
?? ?}
}
?
同樣Iterator也是一個接口,目的是在于把不同集合的遍歷方式抽象出來,這樣我們使用迭代器遍歷的時候,就不需要關注于集合內部結構,能夠使用Iterator的內部方法直接遍歷(也就是說,不管是針對List還是Set的遍歷,我們都能夠直接使用Iterator遍歷拿到集合元素,而不需要關心是List還是Set)。那么這個時候,如果使用的數據結構有所變化,我們不需要去維護原有遍歷集合的代碼,因此也可以理解Iterator是有將集合與集合的遍歷做了一個解耦。
Iterable Iterator兩兄弟的區別
Iterable接口是為了達到實現該接口的類,可以使用foreach循環的目的。
Iterator接口是基于迭代器模式,實現了對聚合類的存儲和遍歷的分離。
兩者所強調的內容不同:
Iterable接口強調的是實現Iterable接口可使用foreach語法遍歷,也可以使用迭代器遍歷。
Iterator接口強調其實現類可使用迭代器遍歷
參考鏈接:https://blog.csdn.net/weixin_45663027/article/details/134135420