How to create a map object in Java?
To create a Map object, you can use the HashMap class.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 创建一个空的Map对象
Map<String, Integer> map1 = new HashMap<>();
// 创建一个带有初始键值对的Map对象
Map<String, Integer> map2 = new HashMap<>();
map2.put("key1", 1);
map2.put("key2", 2);
map2.put("key3", 3);
System.out.println(map1); // 输出 {}
System.out.println(map2); // 输出 {key1=1, key2=2, key3=3}
}
}
In the code above, we created an empty Map object named map1 using new HashMap<>(). We also created another Map object named map2 with initial key-value pairs using new HashMap<>, where the keys are of type String and the values are of type Integer. We added three key-value pairs to map2 using the put method.
Finally, we printed out two Map objects using System.out.println, and we can see that map1 is an empty Map object, while map2 contains three key-value pairs.