Understanding Java Collections – ArrayList, HashSet, and HashMap

 Java provides a robust framework called Collections Framework that helps developers store and manage data efficiently. The core collections are flexible and dynamic, and understanding their behavior is crucial for writing optimized Java code. In this blog, we will dive deep into three widely used collection classes: ArrayList, HashSet, and HashMap.


1. Collections Framework Overview

The Collections Framework in Java provides a well-organized architecture for storing and manipulating data. It includes interfaces and classes for working with different types of data structures such as lists, sets, maps, and more. These collections are found in the java.util package and are used to handle groups of objects with more flexibility than arrays.

Let’s explore three of the most common classes within the Collections Framework:


2. ArrayList – Dynamic Array in Java

An ArrayList is a part of the List interface and is a resizable array in Java. Unlike arrays that have a fixed size, an ArrayList can dynamically grow or shrink as elements are added or removed.

Key Features:

  • Dynamic sizing: It automatically grows when the number of elements exceeds the current capacity.
  • Indexed access: It allows random access to elements using an index (just like arrays).
  • Ordered: It maintains the insertion order of elements.
  • Allows duplicates: You can store duplicate elements in an ArrayList.

Common Operations:

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Apple");  // Duplicate allowed
        
        System.out.println(list);  // Output: [Apple, Banana, Apple]

        list.remove(1);  // Removes "Banana"
        System.out.println(list);  // Output: [Apple, Apple]
        
        System.out.println(list.get(0));  // Accesses element at index 0: Apple
    }
}

Use Cases:

  • Managing ordered data.
  • Frequently accessing elements by index.
  • Situations where duplicates are acceptable.

3. HashSet – Unordered Collection Without Duplicates

A HashSet is part of the Set interface and represents an unordered collection that does not allow duplicate elements. It is implemented using a hash table, which makes operations like insertion, deletion, and lookup very fast (average time complexity of O(1)).

Key Features:

  • No duplicates: Ensures that all elements are unique.
  • Unordered: It does not maintain any specific order of elements.
  • Efficient operations: Fast for add, remove, and contains operations due to hashing.

Common Operations:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Apple");  // Duplicate won't be added

        System.out.println(set);  // Output: [Apple, Banana] (Order may vary)

        set.remove("Banana");  // Removes "Banana"
        System.out.println(set);  // Output: [Apple]
        
        System.out.println(set.contains("Apple"));  // Output: true
    }
}

Use Cases:

  • Maintaining a unique set of elements.
  • Scenarios where ordering of elements doesn’t matter.
  • When fast lookups, insertions, and deletions are required.

4. HashMap – Key-Value Pair Collection

A HashMap is part of the Map interface and stores elements in key-value pairs. Each key is unique, but the values can be duplicated. HashMap uses hashing to store and retrieve data, making it efficient for search operations.

Key Features:

  • Key-value pair storage: Stores mappings between a key and a value.
  • No duplicate keys: Keys must be unique, but values can be duplicated.
  • Unordered: Does not guarantee any order of elements.
  • Null values: It allows one null key and multiple null values.

Common Operations:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Apple", 3);
        map.put("Banana", 2);
        map.put("Apple", 5);  // Replaces the value of "Apple"
        
        System.out.println(map);  // Output: {Apple=5, Banana=2}

        map.remove("Banana");  // Removes the key "Banana"
        System.out.println(map);  // Output: {Apple=5}
        
        System.out.println(map.get("Apple"));  // Output: 5 (value associated with "Apple")
    }
}

Use Cases:

  • Storing mappings between keys and values (e.g., word counts, settings).
  • Efficient lookups based on keys.
  • Situations where each key must map to a single value.

5. Comparison of ArrayList, HashSet, and HashMap




Followers