線性表是最基礎、最常用的數據結構之一。本文詳細講解線性表的順序存儲結構(動態數組實現),並提供功能完整、代碼規範的 Java 泛型實現,涵蓋增刪改查、擴容、遍歷等核心操作。
SequenceList<T> 適配任意引用類型。Arrays.copyOf)。IndexOutOfBoundsException。Object[] elementData 存儲數據,int size 記錄當前元素數,int capacity 記錄數組容量。insert(T element, int index)public void insert(T element, int index) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("數組越界異常");
}
ensureCapacity(size + 1);
// 將 index 及之後元素後移一位
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
delete(int index)public void delete(int index) {
if (index < 0 || index > size - 1) {
throw new IndexOutOfBoundsException("數組越界異常");
}
// 將 index 之後元素前移一位
System.arraycopy(elementData, index + 1, elementData, index, size - index - 1);
size--;
elementData[size] = null; // 幫助 GC 回收
}
ensureCapacity(int minCapacity)private void ensureCapacity(int minCapacity) {
if (minCapacity > capacity) {
capacity = minCapacity + 2; // 留餘量減少擴容頻率
elementData = Arrays.copyOf(elementData, capacity);
}
}
public static void main(String[] args) {
SequenceList<String> list = new SequenceList<>();
System.out.println("isEmpty: " + list.isEmpty()); // true
list.add("3");
list.insert("7", 0); // 頭部插入
System.out.println("length: " + list.length()); // 2
System.out.println("priorElem(1): " + list.priorElem(1)); // 7
System.out.println("nextElem(0): " + list.nextElem(0)); // 3
list.delete(1); // 刪除 "3"
list.clear(); // 清空
}
運行結果截圖:

ReentrantReadWriteLock 或 CopyOnWriteArrayList 思路實現併發安全。Serializable 便於持久化與網絡傳輸。順序存儲結構隨機訪問 O(1)、內存局部性好、適合頻繁讀取、尾部增刪場景;但中間插刪需移動元素 O(n)、容量固定需擴容。掌握其實現細節是理解 ArrayList、Vector 等集合源碼的基石。