Java 集合框架位於 java.util 套件,提供了陣列、鏈表、佇列、堆疊、映射等常用資料結構。整體架構可劃分為四大塊:List 列表、Set 集合、Map 映射、工具類(Iterator、Enumeration、Arrays、Collections)。
Collection<E> 是高度抽象的集合根介面,定義了增、刪、查、遍歷、大小判斷等基本操作。兩大分支:
ArrayList、LinkedList、Vector、Stack。HashSet(基於 HashMap)、TreeSet(基於 TreeMap)。Map<K,V> 代表鍵值對映射,不繼承 Collection。核心實現:
HashMap、TreeMap、WeakHashMap 繼承 AbstractMap。Hashtable 雖繼承 Dictionary,但也實作 Map 介面(線程安全)。Iterator:通用遍歷介面,提供 hasNext()、next()、remove()。採用 fail-fast 機制,併發修改時拋出 ConcurrentModificationException。ListIterator:專為 List 設計,支援雙向遍歷、索引查詢、元素新增/修改。Enumeration:JDK 1.0 遺留介面,功能較弱,僅用於 Vector、Hashtable 等舊類別。| 類別 | 繼承/實作關係 | 主要作用 |
|---|---|---|
AbstractCollection | 實作 Collection | 實作除 iterator()、size() 外所有方法 |
AbstractList | 繼承 AbstractCollection、實作 List | 實作除 size()、get(int) 外所有方法;提供 iterator() 預設實作 |
AbstractSet | 繼承 AbstractCollection、實作 Set | 同 AbstractCollection(Set 無額外 API) |
實作類(如 ArrayList、HashSet)只需繼承對應抽象類並實作少數抽象方法,大幅減少樣板碼。
boolean add(E e)
boolean addAll(Collection<? extends E> c)
void clear()
boolean contains(Object o)
boolean remove(Object o)
int size()
Iterator<E> iterator()
Object[] toArray()
<T> T[] toArray(T[] a)
void add(int index, E element)
E get(int index)
E set(int index, E element)
int indexOf(Object o)
List<E> subList(int from, int to)
ListIterator<E> listIterator()
// Iterator
boolean hasNext()
E next()
void remove()
// ListIterator 額外
boolean hasPrevious()
E previous()
int nextIndex()
int previousIndex()
void add(E e)
void set(E e)
掌握這張架構圖與核心 API,即可在開發中靈活選擇最適合的集合類型,並理解其效能特徵與併發行為。