Java HashMap Usage Guide
In Java, using new HashMap<>() can instantiate a new HashMap object, which can be used to store key-value pair data. HashMap is a commonly used data structure that is implemented based on a hash table, allowing for quick retrieval, insertion, and deletion of key-value pairs. Here is an example usage:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// 创建一个新的HashMap对象
HashMap<String, Integer> map = new HashMap<>();
// 向HashMap中添加键值对
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 15);
// 获取HashMap中的值
int value = map.get("banana");
System.out.println("The value of 'banana' is: " + value);
// 遍历HashMap中的所有键值对
for (String key : map.keySet()) {
int val = map.get(key);
System.out.println(key + ": " + val);
}
}
}
In the example above, we created a new HashMap object called map and added three key-value pairs to it. We then used the map.get(key) method to retrieve the value corresponding to a key and printed out all key-value pairs by iterating through them. HashMap is a very common data structure that is frequently used in Java programming.