What is HashMap
HashMap: In java hashMap is a part of collection. This class will found in java.util package. It provides the basic implementation of the Map interface of Java. HashMap is a data structure that allows you to store data in a key-value pair format. It provides a way to associate keys with values, making it easy to retrieve values using their corresponding keys. If we try to insert the duplicate key in HashMap, it will replace the element of the corresponding key. The basic idea behind a HashMap's hashing mechanism is to convert the key into an integer index that indicates the location in the underlying array where the corresponding value is stored.
syntax of creating HashMap - HashMap<String, String> capitalCities = new HashMap<String, String>();
we need to import HashMap class from java.util
Java HashMap Implementation
Performing Various operation in HashMap:
1.Adding Element in java HashMap: In order to add an element to the map we can use the Put() method . however the insertion order is not retained in the HashMap. Internally for every element , a separate hash is generated and the elements are indexed based on this hash to make it more efficient.
capitalCities.put("England", "landon");
capitalCities.put("India", "Delhi");
2.Changing Element in java HashMap: After adding the elements if we wish to change the element, it can be done by again adding the element with the Put() method. Since the elements in the map are indexed using keys. the value of the key can be changed by simply inserting the updated value for the key which we wish to change.
capitalCities.put("England", "NewYork");
3. Removing Element: In order to remove an element from the map, we can use the remove() method, this method takes the key from the key value and remove the mapping for a key from this map if it is present in the map.
capitalCities.remove("England");
4. Traversal of HashMap: We can use the for loop or Iterator interface to traverse over any structure of the collection framework .
for(String s:capitalCities.keySet()) {
System.out.println("key"+" "+s+" " +"value"+" "+capitalCities.get(s));
}
Why HashMap is efficient :
Let's say you're looking for your friend "matt smith", and I told you he lives on high street.
If you were to go to see if he was home, but didn't know which house you would have to check every house. It could take a long time!
If I told you that everyone who lives on this street lived at the house number that matches the length of their name, you would not bother checking every house, you would go straight to house #10.
That's how hashes work. They hash the key so that when you want to look at the data you don't check everything, you just go directly to the memory address you need.
How the hashing mechanism typically works in a HashMap:
Hash Function: The key is passed through a hash function, which generates a hash code. This hash code is essentially a numeric representation of the key.
Index Calculation: The hash code is then mapped to an index within the HashMap's underlying array. This is often done by applying a secondary hash function or by using the modulo operation with the size of the array to ensure that the index falls within the valid range of array indices.
Handling Collisions: Since different keys might produce the same hash code (known as a collision), HashMaps employ strategies to handle collisions. One common strategy is chaining, where each index in the array corresponds to a linked list (or some other data structure like a tree) of key-value pairs that share the same hash code. Alternatively, open addressing techniques like linear probing or quadratic probing can be used, where collisions are resolved by placing the colliding elements in nearby array slots.
Storage and Retrieval: Once the index is determined, the key-value pair is stored at that index in the array. During retrieval, the same hashing mechanism is applied to the key to find the corresponding index, and then the value associated with that key is returned.
Characteristics of HashMap:
Fast access time: HashMaps provide constant time access to elements, which means that retrieval and insertion of elements are very fast, HashMap store in key-value pair fetching data through HashMap is fast compare to list.
Stores key-value pairs: Each element in a HashMap consists of a key-value pair. The key is used to look up the associated value.
Supports null keys and values: HashMaps allow for null values and keys. This means that a null key can be used to store a value, and a null value can be associated with a key.
Allows duplicates: HashMaps allow for duplicate values, but not duplicate keys. If a duplicate key is added, the previous value associated with the key is overwritten.
Uses hashing function: HashMaps uses a hash function to map keys to indices in an array. This allows for a quick lookup of values based on keys. Methods in HashMap: HashMap class has a number of methods for carrying out actions including adding items, getting value determining whether an element already exists, deleting components and more.
Method | Description |
Put( key, value) | Associates the specified value with the specified key in this map |
remove(0bject key) | Removes the mapping for the specified key from this map if present. |
size() | Returns the number of key-value mappings in this map. |
keySet() | Returns a Set view of the keys contained 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. |
clear() | Removes all of the mappings from this map. |
entrySet() | Returns a Set view of the mappings contained in this map. |
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. |
Advantages of Java HashMap
Fast retrieval: HashMaps provide constant time access to elements, which means that retrieval and insertion of elements is very fast.
Efficient storage: HashMaps use a hashing function to map keys to indices in an array. This allows for quick lookup of values based on keys, and efficient storage of data.
Flexibility: HashMaps allow for null keys and values, and can store key-value pairs of any data type.
Easy to use: HashMaps have a simple interface and can be easily implemented in Java.
Suitable for large data sets: HashMaps can handle large data sets without slowing down.
Disadvantages of Java HashMap:
Unordered: HashMaps are not ordered, which means that the order in which elements are added to the map is not preserved.
Not thread-safe: HashMaps are not thread-safe, which means that if multiple threads access the same hashmap simultaneously, it can lead to data inconsistencies.
Performance can degrade: In some cases, if the hashing function is not properly implemented or if the load factor is too high, the performance of a HashMap can degrade.
More complex than arrays or lists: HashMaps can be more complex to understand and use than simple arrays or lists, especially for beginners.
Higher memory usage: Since HashMaps use an underlying array, they can use more memory than other data structures like arrays or lists. This can be a disadvantage if memory usage is a concern.
Overall, the hashing mechanism allows HashMaps to provide fast average-case time complexity for operations like insertion, deletion, and lookup, typically O(1), although worst-case time complexity can degrade to O(n) in the presence of many collisions and inefficient collision resolution strategies.
コメント