Java Core: Collections Framework - ArrayList, HashMap, HashSet
The Java Collections Framework provides a unified architecture for storing and manipulating groups of objects. It's a crucial part of Java development. Here's a breakdown of three fundamental collection types: ArrayList, HashMap, and HashSet.
1. ArrayList
- Interface:
List - Implementation: Resizable array
- Key Features:
- Ordered: Maintains the order in which elements are inserted.
- Dynamic Size: Automatically grows or shrinks as elements are added or removed.
- Duplicates Allowed: Can contain multiple elements with the same value.
- Index-based Access: Elements can be accessed using their index (position) in the list.
- Searchable: Supports methods like
contains(),indexOf(), andlastIndexOf().
- Use Cases:
- Storing a list of items where order matters (e.g., a to-do list, a sequence of events).
- When you need to access elements frequently by their index.
- When you need to allow duplicate elements.
- Common Methods:
add(E e): Appends the specified element to the end of the list.get(int index): Returns the element at the specified index.remove(int index): Removes the element at the specified index.remove(Object o): Removes the first occurrence of the specified element.size(): Returns the number of elements in the list.contains(Object o): Returnstrueif the list contains the specified element.indexOf(Object o): Returns the index of the first occurrence of the specified element, or -1 if not found.isEmpty(): Checks if the list is empty.
- Example:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("Alice"); // Duplicate allowed
System.out.println("Names: " + names); // Output: [Alice, Bob, Charlie, Alice]
System.out.println("Size: " + names.size()); // Output: 4
System.out.println("Element at index 1: " + names.get(1)); // Output: Bob
System.out.println("Contains Bob: " + names.contains("Bob")); // Output: true
System.out.println("Index of Alice: " + names.indexOf("Alice")); // Output: 0
}
}
2. HashMap
- Interface:
Map - Implementation: Hash table
- Key Features:
- Key-Value Pairs: Stores data as key-value pairs.
- Unordered: Does not guarantee any specific order of elements. (Prior to Java 8, the order was completely unpredictable. From Java 8 onwards, insertion order is preserved, but it's still best not to rely on it for critical logic).
- Unique Keys: Keys must be unique. If you try to insert a duplicate key, the old value will be overwritten.
- Null Keys/Values: Allows one null key and multiple null values.
- Fast Lookup: Provides very fast access to values based on their keys (average O(1) time complexity).
- Use Cases:
- Storing data where you need to quickly retrieve values based on a unique identifier (e.g., a dictionary, a phone book).
- Implementing caches.
- Counting the frequency of items.
- Common Methods:
put(K key, V value): Inserts the specified key-value pair into the map.get(Object key): Returns the value associated with the specified key.remove(Object key): Removes the key-value pair associated with the specified key.containsKey(Object key): Returnstrueif the map contains the specified key.containsValue(Object value): Returnstrueif the map contains the specified value.size(): Returns the number of key-value pairs in the map.isEmpty(): Checks if the map is empty.keySet(): Returns aSetview of the keys in the map.values(): Returns aCollectionview of the values in the map.
- Example:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.put("Charlie", 35);
System.out.println("Ages: " + ages); // Output: {Bob=25, Charlie=35, Alice=30} (order may vary)
System.out.println("Alice's age: " + ages.get("Alice")); // Output: 30
System.out.println("Contains Bob: " + ages.containsKey("Bob")); // Output: true
System.out.println("Size: " + ages.size()); // Output: 3
}
}
3. HashSet
- Interface:
Set - Implementation: Hash table
- Key Features:
- Unordered: Does not guarantee any specific order of elements. (Insertion order is preserved from Java 8 onwards, but it's still best not to rely on it).
- Unique Elements: Does not allow duplicate elements. If you try to add a duplicate, it will be ignored.
- Null Elements: Allows one null element.
- Fast Lookup: Provides very fast checking for the existence of an element (average O(1) time complexity).
- Use Cases:
- Storing a collection of unique items (e.g., a list of unique user IDs, a set of unique words in a document).
- Removing duplicate elements from a collection.
- Checking for membership efficiently.
- Common Methods:
add(E e): Adds the specified element to the set. Returnstrueif the element was added (i.e., it wasn't already present),falseotherwise.remove(Object o): Removes the specified element from the set.contains(Object o): Returnstrueif the set contains the specified element.size(): Returns the number of elements in the set.isEmpty(): Checks if the set is empty.
- Example:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Charlie");
uniqueNames.add("Alice"); // Duplicate - will be ignored
System.out.println("Unique Names: " + uniqueNames); // Output: [Bob, Charlie, Alice] (order may vary)
System.out.println("Size: " + uniqueNames.size()); // Output: 3
System.out.println("Contains Charlie: " + uniqueNames.contains("Charlie")); // Output: true
}
}
Key Differences Summarized:
| Feature | ArrayList | HashMap | HashSet |
|---|---|---|---|
| Interface | List |
Map |
Set |
| Order | Ordered | Unordered (Insertion order preserved from Java 8, but don't rely on it) | Unordered (Insertion order preserved from Java 8, but don't rely on it) |
| Duplicates | Allowed | Keys must be unique | Not allowed |
| Data Structure | Resizable Array | Hash Table | Hash Table |
| Access | Index-based | Key-based | Element-based |
| Key-Value | No | Yes | No |
Choosing the right collection depends on your specific needs. Consider whether you need to maintain order, allow duplicates, and how you'll be accessing the data. Understanding these differences is fundamental to writing efficient and effective Java code.