Logo
TUTORIAL

Java Collections Framework

What is the Collections Framework?
It is a unified architecture for representing and manipulating collections. It allows you to store, retrieve, and manipulate groups of data (objects) efficiently.

1. The ArrayList (Dynamic Array)

The ArrayList class is a resizable array. While a standard array is fixed in size, an ArrayList grows automatically as you add elements.

import java.util.ArrayList; // Step 1: Import public class ListDemo { public static void main(String[] args) { ArrayList students = new ArrayList<>(); // Step 2: Add elements students.add("John"); students.add("Jane"); students.add("Craby"); // Step 3: Access and Remove System.out.println("Student at index 0: " + students.get(0)); students.remove("Jane"); System.out.println("List Size: " + students.size()); } }
// Output:
Student at index 0: John
List Size: 2

2. The HashMap (Key-Value Pairs)

A HashMap stores items in "Key/Value" pairs. You can access them by an index of another type (e.g., a String). Think of it like a real dictionary: the word is the Key, and the definition is the Value.

import java.util.HashMap; public class MapDemo { public static void main(String[] args) { HashMap userAges = new HashMap<>(); // Add keys and values (Name, Age) userAges.put("Alice", 25); userAges.put("Bob", 30); // Accessing a value using its key System.out.println("Alice's Age: " + userAges.get("Alice")); } }
// Output:
Alice's Age: 25

3. Key Theory: List vs. Set

Human Note: Why use these? In modern development, we almost never use standard Arrays. Whether you are building an Android app or a web server, ArrayList and HashMap are your best friends for handling data that changes over time.