Skip to content

Commit ca3b4f7

Browse files
committed
Update CH13.md
1 parent fd1329a commit ca3b4f7

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

docs/CH13.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,34 @@ Collection 結構可持有各自獨立的物件,在 Java SE 中, Collection
1414

1515
java.util.ArrayList 類別實作了 java.util.List 介面,所以要先認識一下 List 介面,List 介面是 java.util.Collection 介面的子介面,而 Collection 介面則是 java.lang.Iterable 的子介面,Iterable 介面要求實作一個 iterator() 方法。
1616

17+
```java
1718
package java.lang;
1819
import java.util.Iterator;
1920
public interface Iterable<T> {
2021
Iterator<T> iterator();
2122
}
23+
```
2224

2325
從 J2SE 5.0 開始增加了泛型設計的新功能,所以像 Iterable、Collection 相關介面與其實作類別,都使用泛型的功能重新改寫了,因而您可以在原始碼或是 API 文件中看到增加了不少與泛型相關的功能或說明。
2426

2527
Iterable 介面要求實作它的類別傳回一個實作 java.util.Iterator 介面的物件,事實上您在 Java SE 的 API 中找不到任何實作 Iterator 的類別,因為 Iterator 會根據實際的容器資料結構來迭代元素,而容器的資料結構實作方式對外界是隱藏的,使用者不用知道這個結構,只需要知道 Iterator 的操作方法,就可以取出元素,Iterator 介面的定義如下:
2628

29+
```java
2730
package java.util;
2831
public interface Iterator<E> {
2932
boolean hasNext();
3033
E next();
3134
void remove();
3235
}
36+
```
3337

3438
> **良葛格的話匣子** Iterator 是「Iterator 模式」的一個實例,有關 Iterator 模式,請參考我網站上的文件:
3539
>
3640
> - http://openhome.cc/Gossip/DesignPattern/
3741
3842
Collection 介面繼承了 Iterator 介面,定義了加入元素、移除元素、元素長度等方法,
3943

44+
```java
4045
package java.util;
4146
public interface Collection<E> extends Iterable<E> {
4247
int size();
@@ -54,9 +59,11 @@ Collection 介面繼承了 Iterator 介面,定義了加入元素、移除元
5459
boolean equals(Object o);
5560
int hashCode();
5661
}
62+
```
5763

5864
Collection 在移除元素及取得元素上的定義是比較通用,List 介面則又增加了根據索引取得物件的方法,這說明了 List 資料結構的特性,每個加入 List 中的元素是循序加入的,並可指定索引來存取元素(以下原始碼只是節錄部份)。
5965

66+
```java
6067
package java.util;
6168
public interface List<E> extends Collection<E> {
6269
....
@@ -70,6 +77,7 @@ Collection 在移除元素及取得元素上的定義是比較通用,List 介
7077
List<E> subList(int fromIndex, int toIndex);
7178
....
7279
}
80+
```
7381

7482
List 資料結構的特性是,每個加入 List 中的元素是循序加入的,並可指定索引來存取元素,List 可以使用陣列(Array)或是鏈結串列(Linked List)來實作這個特性,前者在 Java SE 中的實作就是 java.util.ArrayList,後者就是 java.util.LinkedList,對於循序加入與存取,使用 ArrayList 的效率比較好,對於經常變動元素排列順序的需求,使用 LinkedList 會比較好。
7583

0 commit comments

Comments
 (0)