C# Java HashMap equivalent
In Java, the HashMap class is the equivalent of the Dictionary
class in C#. It is a map data structure that stores (key, value) pairs and provides fast lookup and insertion of elements.
Here's an example of how you can use a HashMap in Java:
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
// Add some elements to the map
map.put("Alice", 42);
map.put("Bob", 23);
map.put("Eve", 56);
// Look up an element by key
int age = map.get("Alice");
System.out.println(age); // 42
// Check if the map contains a key
boolean containsKey = map.containsKey("Charlie");
System.out.println(containsKey); // false
// Get the size of the map
int size = map.size();
System.out.println(size); // 3
The HashMap class is part of the java.util
package, and it is not synchronized, so it is not thread-safe. If you need a thread-safe map, you can use the ConcurrentHashMap
class from the java.util.concurrent
package.
import java.util.concurrent.ConcurrentHashMap;
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
The ConcurrentHashMap
class provides thread-safe access to the map, but it may be slightly slower than the HashMap class.