Collection Kit

ArrayList

Linear

An ArrayList is a resizable array implementation of the List interface. It allows for dynamic resizing, meaning that the size of the array can grow or shrink as elements are added or removed. ArrayLists provide fast random access to elements, as they are stored in contiguous memory locations, making it efficient to retrieve elements by their index. However, inserting or deleting elements, especially in the middle of the list, can be less efficient due to the need to shift elements.

Import Statement
import { ArrayList } from "collection-kit";

Key Features

  • Dynamic Sizing: Automatically resizes when elements are added or removed.
  • Random Access: Provides O(1) time complexity for accessing elements by index.
  • Insertion/Deletion: Insertion and deletion operations can take O(n) time in the worst case, as elements may need to be shifted.
  • Memory Efficiency: Uses contiguous memory, which can lead to better cache performance compared to linked structures.

Common Operations

Add
Append an element to the end of the list or insert it at a specific index.
Remove
Delete an element from the list by value or index.
Get
Retrieve an element at a specific index.
Set
Update the value of an element at a specific index.
Size
Return the number of elements in the list.

Example Code

import { ArrayList } from "collection-kit";

const list = new ArrayList();
list.add(10);
list.add(20);
list.add(30);

console.log("Size:", list.size());        // 3
console.log("First element:", list.get(0)); // 10

// Iterate through elements
for (let i = 0; i < list.size(); i++) {
  console.log(`Element ${i}:`, list.get(i));
}