Introduction to HashMap
A HashMap
in Java is part of the java.util
package and provides the basic implementation of the Map
interface. It stores data in key-value pairs, allowing for efficient retrieval, insertion, and deletion of elements based on keys.
Key Concepts
- Key-Value Pair: Each element in a
HashMap
is stored as a key-value pair. - Hashing:
HashMap
uses a technique called hashing to store elements. Hashing converts the key into a hash code, which determines the index in the array where the value is stored. - Null Values:
HashMap
allows one null key and multiple null values. - Non-Synchronized:
HashMap
is not synchronized, meaning it is not thread-safe. For thread-safe operations, consider usingConcurrentHashMap
.
Basic Operations
- Insertion: Adding key-value pairs to the
HashMap
. - Retrieval: Accessing values based on their keys.
- Deletion: Removing key-value pairs from the
HashMap
. - Iteration: Traversing through the key-value pairs.
Creating a HashMap
To create a HashMap
, you need to import the java.util.HashMap
class and instantiate it.
import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { // Creating a HashMap HashMap<Integer, String> map = new HashMap<>(); // Adding key-value pairs map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Retrieving a value String value = map.get(2); System.out.println("Value for key 2: " + value); // Removing a key-value pair map.remove(3); // Iterating through the HashMap for (Integer key : map.keySet()) { System.out.println("Key: " + key + ", Value: " + map.get(key)); } } }
Explanation
- Creating a HashMap:
HashMap<Integer, String> map = new HashMap<>();
creates aHashMap
where keys are of typeInteger
and values are of typeString
. - Adding key-value pairs:
map.put(1, "Apple");
adds the key1
with the value"Apple"
to theHashMap
. - Retrieving a value:
map.get(2);
retrieves the value associated with the key2
. - Removing a key-value pair:
map.remove(3);
removes the key-value pair with the key3
. - Iterating through the HashMap: The
for
loop iterates through the keys of theHashMap
and prints each key-value pair.
Common Methods
Method | Description |
---|---|
put(K key, V value) |
Associates the specified value with the specified key in this map. |
get(Object key) |
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. |
remove(Object key) |
Removes the mapping for a key from this map if it is present. |
containsKey(Object key) |
Returns true if this map contains a mapping for the specified key. |
containsValue(Object value) |
Returns true if this map maps one or more keys to the specified value. |
keySet() |
Returns a Set view of the keys contained in this map. |
values() |
Returns a Collection view of the values contained in this map. |
entrySet() |
Returns a Set view of the mappings contained in this map. |
Practical Exercises
Exercise 1: Basic Operations
Task: Create a HashMap
to store student IDs (Integer) and their names (String). Perform the following operations:
- Add five students to the
HashMap
. - Retrieve and print the name of a student using their ID.
- Remove a student from the
HashMap
using their ID. - Print all the student IDs and names.
Solution:
import java.util.HashMap; public class StudentHashMap { public static void main(String[] args) { // Creating a HashMap HashMap<Integer, String> students = new HashMap<>(); // Adding students students.put(101, "Alice"); students.put(102, "Bob"); students.put(103, "Charlie"); students.put(104, "David"); students.put(105, "Eve"); // Retrieving a student's name String studentName = students.get(102); System.out.println("Student with ID 102: " + studentName); // Removing a student students.remove(104); // Printing all students for (Integer id : students.keySet()) { System.out.println("ID: " + id + ", Name: " + students.get(id)); } } }
Exercise 2: Checking for Keys and Values
Task: Modify the previous exercise to check if a student ID exists in the HashMap
before retrieving or removing a student. Also, check if a particular student name exists in the HashMap
.
Solution:
import java.util.HashMap; public class StudentHashMap { public static void main(String[] args) { // Creating a HashMap HashMap<Integer, String> students = new HashMap<>(); // Adding students students.put(101, "Alice"); students.put(102, "Bob"); students.put(103, "Charlie"); students.put(104, "David"); students.put(105, "Eve"); // Checking if a student ID exists before retrieving int idToRetrieve = 102; if (students.containsKey(idToRetrieve)) { String studentName = students.get(idToRetrieve); System.out.println("Student with ID " + idToRetrieve + ": " + studentName); } else { System.out.println("Student with ID " + idToRetrieve + " not found."); } // Checking if a student ID exists before removing int idToRemove = 104; if (students.containsKey(idToRemove)) { students.remove(idToRemove); System.out.println("Student with ID " + idToRemove + " removed."); } else { System.out.println("Student with ID " + idToRemove + " not found."); } // Checking if a student name exists String nameToCheck = "Eve"; if (students.containsValue(nameToCheck)) { System.out.println("Student with name " + nameToCheck + " exists."); } else { System.out.println("Student with name " + nameToCheck + " not found."); } // Printing all students for (Integer id : students.keySet()) { System.out.println("ID: " + id + ", Name: " + students.get(id)); } } }
Common Mistakes and Tips
- Null Keys and Values: Remember that
HashMap
allows one null key and multiple null values. Be cautious when using null keys and values as they can lead toNullPointerException
in some cases. - Iteration: When iterating through a
HashMap
, avoid modifying the map (e.g., adding or removing elements) to preventConcurrentModificationException
. - Thread Safety:
HashMap
is not synchronized. If you need a thread-safe map, consider usingConcurrentHashMap
or wrapping theHashMap
withCollections.synchronizedMap
.
Conclusion
In this section, you learned about the HashMap
class in Java, including its basic operations, common methods, and practical usage. You also practiced creating and manipulating HashMap
instances through exercises. Understanding HashMap
is crucial for efficient data storage and retrieval in Java applications. In the next section, you will explore other data structures and collections in Java.
Java Programming Course
Module 1: Introduction to Java
- Introduction to Java
- Setting Up the Development Environment
- Basic Syntax and Structure
- Variables and Data Types
- Operators
Module 2: Control Flow
Module 3: Object-Oriented Programming
- Introduction to OOP
- Classes and Objects
- Methods
- Constructors
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Module 4: Advanced Object-Oriented Programming
Module 5: Data Structures and Collections
Module 6: Exception Handling
Module 7: File I/O
Module 8: Multithreading and Concurrency
- Introduction to Multithreading
- Creating Threads
- Thread Lifecycle
- Synchronization
- Concurrency Utilities
Module 9: Networking
- Introduction to Networking
- Sockets
- ServerSocket
- DatagramSocket and DatagramPacket
- URL and HttpURLConnection