HashMap and its Implementation
The HashMap
class in Java is an implementation of the Map
interface and provides a way to store key-value pairs. It allows you to insert, retrieve, and delete elements based on the key.
Creating a HashMap
To create a HashMap
, you need to declare a variable of type Map
and instantiate it with the HashMap
class:
1Map<String, Integer> hashMap = new HashMap<>();
In this example, the String
type is used for the keys, and the Integer
type is used for the values. You can choose different types for your keys and values based on your requirements.
Adding Elements to a HashMap
You can add elements to a HashMap
using the put
method. The put
method takes two parameters: the key and the value.
1hashMap.put("key", value);
For example, let's add some key-value pairs to the HashMap
:
1hashMap.put("one", 1);
2hashMap.put("two", 2);
3hashMap.put("three", 3);
Accessing Elements from a HashMap
You can access elements from a HashMap
using the get
method. The get
method takes the key as a parameter and returns the corresponding value.
1int value = hashMap.get("key");
For example, let's access the values of the key-value pairs we added earlier:
1int value1 = hashMap.get("one");
2int value2 = hashMap.get("two");
3int value3 = hashMap.get("three");
Output
When you run the above code, the output will be:
1Value of 'one': 1
2Value of 'two': 2
3Value of 'three': 3
You can see that the values are retrieved based on the keys.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> hashMap = new HashMap<>();
// Add key-value pairs to the HashMap
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);
// Access values from the HashMap
int value1 = hashMap.get("one");
int value2 = hashMap.get("two");
int value3 = hashMap.get("three");
// Print the values
System.out.println("Value of 'one': " + value1);
System.out.println("Value of 'two': " + value2);
System.out.println("Value of 'three': " + value3);
}
}