參考 Java ArrayList API 設計,以下為常用方法摘要:
| 方法 | 說明 |
|---|---|
add(E e) | 在尾部新增元素 |
add(index, E) | 在指定位置插入元素 |
addAll(Collection) | 批次新增集合元素到尾部 |
addAll(index, Collection) | 從指定位置批次插入 |
clear() | 移除所有元素 |
clone() | 回傳淺層複製 |
contains(Object) | 檢查是否包含指定元素 |
ensureCapacity(int) | 確保最小容量 |
get(index) | 取得指定位置元素 |
indexOf(Object) | 首次出現索引,無則 -1 |
isEmpty() | 是否為空列表 |
lastIndexOf(Object) | 最後出現索引 |
remove(index) | 移除指定位置元素 |
remove(Object) | 移除首次出現的指定元素 |
set(index, E) | 替換指定位置元素 |
size() | 回傳元素數量 |
toArray() | 轉為陣列 |
trimToSize() | 調整容量為當前大小 |
function ArrayList() {
this.arr = [];
// 回傳元素數量
this.size = function() {
return this.arr.length;
};
// 新增元素(支援單一新增、指定位置插入)
this.add = function() {
if (arguments.length === 1) {
this.arr.push(arguments[0]);
} else if (arguments.length >= 2) {
// arguments[0] = index, arguments[1] = value
this.arr.splice(arguments[0], 0, arguments[1]);
}
return this; // 支援鏈式呼叫
};
// 取得指定索引元素
this.get = function(index) {
return this.arr[index];
};
// 移除指定索引元素
this.removeIndex = function(index) {
this.arr.splice(index, 1);
};
// 移除指定物件(首次出現)
this.removeObj = function(obj) {
this.removeIndex(this.indexOf(obj));
};
// 查找元素首次出現索引
this.indexOf = function(obj) {
for (var i = 0; i < this.arr.length; i++) {
if (this.arr[i] === obj) return i;
}
return -1;
};
// 判斷是否為空
this.isEmpty = function() {
return this.arr.length === 0;
};
// 清空列表
this.clear = function() {
this.arr = [];
};
// 檢查是否包含元素
this.contains = function(obj) {
return this.indexOf(obj) !== -1;
};
}
// 建立實例
var list = new ArrayList();
// 鏈式新增
list.add("0").add("1").add("2").add("3");
// 指定位置插入(索引 2 插入 "22222222222")
list.add(2, "22222222222");
// 移除指定值
list.removeObj("3");
// 移除指定索引
list.removeIndex(0);
// 遍歷輸出
for (var i = 0; i < list.size(); i++) {
document.writeln(list.get(i) + "
");
}
// 檢查包含
document.writeln("包含 '2': " + list.contains("2"));
1 22222222222 2 包含 '2': true
index 邊界檢查,拋出自訂異常ensureCapacity 預分配class ArrayList 語法更符合現代規範for...of 迴圈與展開運算子現代 JavaScript 陣列已內建豐富方法(push/splice/filter/map/find 等),大多數場景直接使用原生陣列即可。此實作主要用於理解資料結構原理、遷移 Java 代碼、或需強型別語義的場景。