Search⌘ K
AI Features

Working with ArrayList, HashSet, and HashMap

Explore how to effectively use ArrayList for dynamic ordered data, HashSet for unique elements, and HashMap for key-value pairs in Java. This lesson helps you understand their core operations add get remove and performance characteristics so you can select the best collection for your application needs.

Arrays are the foundational building blocks of data storage in Java, but they are rigid. You must define their size upfront, and that size cannot change. In the real world, data is dynamic: users sign up, shopping carts grow, and log files expand. We rarely know exactly how many items we will need to store when we write the code.

To manage varying data storage and retrieval needs, we use the Java Collections Framework. The framework offers many specialized tools, but for most use cases, you’ll rely on three core implementations: ArrayList for dynamic arrays, HashSet for unique collections, and HashMap for key-value pairs. Choosing the right implementation affects both the complexity of your code and its runtime performance.

The resizable array (ArrayList)

The ArrayList is the most widely used collection in Java. You can think of it as a smart array that automatically resizes itself as you add or remove elements. Like a standard array, it maintains a specific order (insertion order) and allows you to access elements instantly if you know their position (index).

To use an ArrayList, we must specify the type of data it will hold using generics the <Type> syntax. This enforces type safety, ensuring we do not accidentally store an Integer in a list intended for String values.

In the example below, we manage a dynamic list of todo items. Notice that we can add duplicates, and the list preserves the order in which we added them. Beyond just adding items, ArrayList provides methods to modify items at specific positions (set), check the ...

Java 25
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
// Create a list restricted to String objects
ArrayList<String> todoList = new ArrayList<>();
// Adding elements
todoList.add("Buy groceries");
todoList.add("Walk the dog");
todoList.add("Buy groceries"); // Duplicates are allowed
// Accessing by index (0-based)
String firstItem = todoList.get(0);
// Modifying an element at a specific index
todoList.set(1, "Feed the cat");
// Checking size
System.out.println("Items to do: " + todoList.size());
System.out.println("First item: " + firstItem);
System.out.println("Full list: " + todoList);
}
}
...