Understanding Java Collection Framework: Set and Map Interfaces
Overview of Java Collections
The Java Collections Framework is categorized primarily into three structures: Set, List, and Map. Set containers handle unordered collections with unique elements, List maintains ordered sequences that permit duplicates, and Map manages key-value pairs.
The Set Interface and HashSet Implementation
Set objects extend the Collection interface without adding extra methods, focusing on the strict enforcement of element uniqueness. A HashSet stores data using a hash table approach, offering high performance for rterieval and insertion operations.
Internal consisetncy in a HashSet relies on two methods: hashCode() to determine storage slots and equals() to verify object identity. An element is only considered a duplicate if both the hash code matches and the equality check returns true.
import java.util.HashSet;
import java.util.Iterator;
public class SetDemo {
public static void main(String[] args) {
HashSet<String> identifiers = new HashSet<>();
identifiers.add("Alpha");
identifiers.add("Beta");
identifiers.add("Gamma");
Iterator<String> iterator = identifiers.iterator();
while (iterator.hasNext()) {
System.out.println("Element: " + iterator.next());
}
}
}
The Map Interface and HashMap Implementation
HashMap utilizes an array and linked list architecture to map unique keys to specific values. It is highly efficient for lookup operations when the associated key is known.
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> inventory = new HashMap<>();
inventory.put("WidgetA", 100);
inventory.put("WidgetB", 250);
// Accessing values via keys
System.out.println("Stock for WidgetA: " + inventory.get("WidgetA"));
// Iterating through entries
for (Map.Entry<String, Integer> entry : inventory.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
Key Collection Operations
The Collection interface provides foundational methods used across List and Set implementations:
add(E e): Inserts an element into the collection.clear(): Removes all entries, resetting size to zero.contains(Object o): Checks for the existance of an object.isEmpty(): Returns true if the collection is empty.remove(Object o): Deletes the specified element.size(): Returns the total count of elements.
Traversal with the Iterator Interface
The Iterator interface provides a standardized way to traverse elements safely:
hasNext(): Checks if the iteration has more elements.next(): Retrieves the subsequent element.remove(): Deletes the last element returned by the iterator from the underlying collection.