Back to JavaScript
2025-12-236 min read

ArrayList (JavaScript)

Learn ArrayList (JavaScript) step by step with clear examples and exercises.

Why This Matters

JavaScript, being a dynamic and high-level programming language, doesn't provide built-in support for arrays like some other languages (such as Java). While JavaScript arrays are flexible and powerful, they have certain limitations, such as dynamically resizing the array size and handling multiple data types. To overcome these limitations, developers often use third-party libraries like es6-array-iterator or lodash to work with arrays more efficiently. However, one such library that provides an ArrayList is the js-collections library.

In this lesson, we will learn about JavaScript's js-collections library and explore its ArrayList functionality, along with practical examples, common mistakes, and practice questions. By understanding ArrayLists, you can work with arrays more efficiently and effectively in your JavaScript projects.

Prerequisites

To follow along with this lesson, you should have a basic understanding of the following concepts:

  1. JavaScript syntax and variables
  2. Basic data structures like arrays and objects
  3. Control flow statements (if-else, for loops, etc.)
  4. Function declarations and arrow functions
  5. Understanding of ES6 features like let, const, template literals, and arrow functions
  6. Familiarity with the concept of arrays in JavaScript

Core Concept

The js-collections library is a lightweight JavaScript library that provides array-like structures with additional functionality. One such structure is the ArrayList, which behaves similar to Java's ArrayList but has some differences due to JavaScript's dynamic nature.

Creating an ArrayList

To create an ArrayList in JavaScript using the js-collections library, first, you need to include the library by adding a script tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/js-collections/2.0.3/js-collections.min.js"></script>

Now, you can create an ArrayList using the ArrayList constructor:

const arrayList = new ArrayList();

Adding and Removing Elements

You can add elements to the ArrayList using the add() method. To remove an element, use the removeAt() method.

// Adding elements
arrayList.add("apple");
arrayList.add(42);
arrayList.add({ name: "John" });

console.log(arrayList); // [ 'apple', 42, { name: 'John' } ]

// Removing an element
arrayList.removeAt(1);
console.log(arrayList); // [ 'apple', { name: 'John' } ]

Accessing Elements

To access elements in the ArrayList, use the get() method. However, unlike arrays, JavaScript doesn't have a built-in way to check if an index is out of bounds. So, it's essential to handle such cases properly:

console.log(arrayList.get(0)); // 'apple'
console.log(arrayList.get(1)); // undefined (since we removed the element at index 1)

ArrayList Methods

The js-collections library provides various methods for working with ArrayLists, such as:

  • size(): Returns the size of the ArrayList.
  • isEmpty(): Checks if the ArrayList is empty.
  • clear(): Removes all elements from the ArrayList.
  • contains(): Checks if an element exists in the ArrayList.
  • indexOf(): Searches for the first occurrence of an element and returns its index.
  • lastIndexOf(): Searches for the last occurrence of an element and returns its index.
  • toArray(): Converts the ArrayList to a regular JavaScript array.
  • addAll(array): Adds all elements from another array to the current ArrayList.
  • removeAll(element): Removes all occurrences of a specific element from the ArrayList.
  • retainAll(array): Retains only the common elements between two arrays (ArrayLists).
  • subList(start, end): Returns a new ArrayList with elements from the specified range.

Worked Example

Let's create an ArrayList, add some elements, perform various operations, and convert it to a regular JavaScript array:

const arrayList = new ArrayList();
arrayList.add("apple");
arrayList.add(42);
arrayList.add({ name: "John" });
arrayList.add("banana");
console.log(arrayList); // [ 'apple', 42, { name: 'John' }, 'banana' ]

// Access elements
console.log(arrayList.get(0)); // 'apple'
console.log(arrayList.get(3)); // 'banana'

// Remove an element
arrayList.removeAt(2);
console.log(arrayList); // [ 'apple', 42, 'banana' ]

// Check size and emptiness
console.log(arrayList.size()); // 3
console.log(arrayList.isEmpty()); // false

// Contains check
console.log(arrayList.contains("apple")); // true
console.log(arrayList.contains("orange")); // false

// IndexOf and LastIndexOf
console.log(arrayList.indexOf("banana")); // 2
console.log(arrayList.lastIndexOf("apple")); // 0

// Clear ArrayList
arrayList.clear();
console.log(arrayList); // []

// Convert to a regular JavaScript array
const arr = arrayList.toArray();
console.log(arr); // []

// Adding elements from another array
const otherArray = ["orange", 3.14];
arrayList.addAll(otherArray);
console.log(arrayList); // [ 'orange', 3.14 ]

// Removing all occurrences of an element
arrayList.removeAll("orange");
console.log(arrayList); // [ 3.14 ]

// Retaining common elements between two arrays
const anotherArrayList = new ArrayList([1, 2, 3, 4]);
const commonElements = arrayList.retainAll(anotherArrayList);
console.log(commonElements); // [] (no common elements)

// Sublist example
const subList = arrayList.subList(0, 2);
console.log(subList); // [ 3.14 ] (only one element since the original ArrayList is empty after removing all elements)

Common Mistakes

  1. Forgetting to include the js-collections library: Without the library, you won't be able to use ArrayList functionality.
  2. Treating ArrayList like a regular JavaScript array: Be aware that ArrayList has additional methods and behaves differently from arrays in some cases (e.g., handling out-of-bounds indexes).
  3. Not handling out-of-bounds indexes: Always check if the index is within the bounds of the ArrayList before accessing elements to avoid errors and unexpected behavior.
  4. Using push() and pop() methods on ArrayList: These methods are array methods, but they don't work with ArrayLists in the js-collections library. Instead, use the add() method to add elements.
  5. Assuming that ArrayList behaves exactly like Java's ArrayList: While there are similarities, JavaScript's dynamic nature means that some differences may exist between the two.

Practice Questions

  1. Create an ArrayList containing numbers from 1 to 5. Remove the number at index 3. What will be the output of console.log(arrayList)?
  2. Write a function that takes an ArrayList as input, finds the sum of all elements, and returns it.
  3. Create an ArrayList containing objects with names and ages. Write a function that sorts the ArrayList based on age.
  4. Given an ArrayList containing strings, write a function that removes all duplicate values.
  5. Write a function that takes an ArrayList as input and reverses its order.
  6. Write a function that checks if two ArrayLists have the same elements (ignoring their order).
  7. Write a function that merges two ArrayLists into one, keeping the original order of elements in each arraylist.
  8. Write a function that takes an ArrayList as input and returns a new ArrayList containing only the odd-indexed elements.
  9. Write a function that takes an ArrayList as input and returns a new ArrayList containing only the even-indexed elements.
  10. Write a function that takes an ArrayList as input and removes all elements that are less than a specified value (e.g., remove all numbers less than 10 from an ArrayList of numbers).

FAQ

  1. Why use JavaScript's js-collections library instead of native Array methods?
  • The js-collections library provides additional functionality, such as ArrayList, that are not available with regular JavaScript arrays. It also simplifies common array operations and offers a more intuitive API for working with collections.
  1. Can I use other libraries like lodash or es6-array-iterator for ArrayList functionality in JavaScript?
  • Yes, you can use other libraries to work with arrays more efficiently, but the js-collections library is a lightweight option specifically designed for ArrayList functionality.
  1. What happens if I try to access an element at an out-of-bounds index in an ArrayList?
  • By default, JavaScript will return undefined. However, it's essential to handle such cases properly to avoid errors and unexpected behavior. In the js-collections library, you can use the getOrDefault() method to provide a default value when accessing out-of-bounds elements.
  1. Can I use the push() method with an ArrayList in the js-collections library?
  • No, the push() method is not supported for ArrayLists in this library. Instead, you can use the add() method to add elements.
  1. Is it possible to sort an ArrayList based on a custom comparison function in JavaScript's js-collections library?
  • Yes, you can provide a custom comparison function when using the sort() method on an ArrayList in the js-collections library. This allows for more flexible sorting options beyond the default alphabetical or numerical order.
ArrayList (JavaScript) | JavaScript | XQA Learn