HashMap in Java
HashMap is a collection class in Java that implements the Map interface, which allows you to store key-value pairs in a hash table. It uses a hash function to generate a hash code for each key, which is used to index the value in the underlying array.
Here's an example of how to create a HashMap in Java:
typescriptimport java.util.HashMap;
public class Example {
public static void main(String[] args) {
// Create a new HashMap
HashMap<String, Integer> myHashMap = new HashMap<>();
// Add some key-value pairs
myHashMap.put("John", 25);
myHashMap.put("Jane", 30);
myHashMap.put("Bob", 20);
// Retrieve a value based on a key
System.out.println("John's age is " + myHashMap.get("John"));
// Iterate over the keys and values in the map
for (String key : myHashMap.keySet()) {
System.out.println(key + " is " + myHashMap.get(key) + " years old.");
}
}
}
In this example, we create a HashMap with String keys and Integer values. We then add three key-value pairs to the map, retrieve the value associated with the key "John", and iterate over all the key-value pairs in the map.
HashMap provides constant-time performance for basic operations like get() and put(), but the performance can degrade when the hash table needs to be resized. It is also not thread-safe, so if you need to use it in a multi-threaded environment, you should use a ConcurrentHashMap instead.
Comments
Post a Comment