The HashMap
class in Java is a implementation of the Map
interface that stores key-value pairs in a hash table. It allows you to store and retrieve elements based on a key, and provides constant-time performance for the basic operations (get and put).
Here is an example of how to use a HashMap
in Java:
import java.util.HashMap; public class Main { public static void main(String[] args) { // Create a HashMap HashMap<String, Integer> map = new HashMap<>(); // Add some elements to the map map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); // Retrieve an element from the map int value = map.get("banana"); System.out.println("The value for 'banana' is: " + value); // Remove an element from the map map.remove("apple"); // Check if the map contains a specific key boolean containsKey = map.containsKey("orange"); System.out.println("The map contains the key 'orange': " + containsKey); } }
In this example, we create a HashMap
that maps strings (the keys) to integers (the values). We add some elements to the map, retrieve an element by its key, remove an element from the map, and check if the map contains a specific key.
Note that the HashMap
class is not synchronized, which means that it is not thread-safe. If you need a thread-safe map, you can use the Collections.synchronizedMap()
method to wrap a HashMap
in a synchronized map.