📅  最后修改于: 2023-12-03 15:31:06.513000             🧑  作者: Mango
Hashmap in Java is a data structure that allows you to store and retrieve data based on a key-value pair. It is implemented based on the hash table data structure, which provides constant-time performance for both adding and retrieving elements.
To declare a Hashmap in Java, you need to import the java.util.HashMap
package and create an instance of the HashMap
class.
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
Here, we are creating a Hashmap that stores keys as String
and values as Integer
.
To add elements to a Hashmap, you can use the put()
method provided by the HashMap
class.
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
Here, we are adding three elements to our HashMap
.
To retrieve elements from a Hashmap, you can use the get()
method provided by the HashMap
class.
int value = map.get("Two");
Here, we are retrieving the value of the key "Two"
, which is 2
.
To remove elements from a Hashmap, you can use the remove()
method provided by the HashMap
class.
map.remove("Three");
Here, we are removing the key-value pair associated with the key "Three"
.
Hashmap in Java is a powerful data structure that allows you to store and retrieve data based on a key-value pair. It provides constant-time performance for both adding and retrieving elements, making it an ideal choice for many applications. If you are interested in learning more about Hashmap, I recommend reading the Java documentation or taking an online course on data structures and algorithms.