- Definition:
- HashMap is a part of the Java Collections Framework.
- It implements the Map interface and stores data in key-value pairs.
2. Key Features:
- It allows null values and a single null key.
- It does not guarantee the order of elements.
3. Key and Value:
- Each key in a HashMap must be unique.
- Values can be duplicated.
4. Performance:
- Provides constant-time performance for basic operations like get and put, on average.
- The actual performance depends on factors like the capacity and hash function quality.
5. Methods:
put(key, value)
: Inserts a key-value pair into the HashMap.get(key)
: Retrieves the value associated with the specified key.remove(key)
: Removes the key and its associated value.containsKey(key)
: Checks if the HashMap contains a specific key.containsValue(value)
: Checks if the HashMap contains a specific value.size()
: Returns the number of key-value pairs in the HashMap.keySet()
: Returns a Set of all keys in the HashMap.
6. Iterating Over HashMap:
- You can iterate over the keys, values, or entries (key-value pairs) using iterators or the enhanced for loop.
7. Load Factor and Capacity:
- The load factor determines when the HashMap should resize.
- The default load factor is 0.75, and the default initial capacity is 16.
8. Collisions:
- Hash collisions occur when multiple keys hash to the same index.
- HashMap uses a linked list (or a red-black tree in Java 8 and later) to handle collisions.
9. Synchronization:
- HashMap is not synchronized, meaning it is not thread-safe.
- For thread-safe operations, consider using
ConcurrentHashMap
or synchronizing the HashMap externally.
10. Recommended Use:
- HashMap is commonly used when you need a fast, efficient way to look up values based on keys.
- For thread-safe and concurrent applications, consider alternatives like
ConcurrentHashMap
or synchronization.