温馨提示×

hashmap初始化的方式有哪些

小亿
106
2024-03-11 14:55:24
栏目: 编程语言

  1. 使用HashMap类的构造方法创建一个空的HashMap对象:
HashMap<String, Integer> map = new HashMap<>();
  1. 使用HashMap类的构造方法创建一个包含指定初始容量和负载因子的HashMap对象:
HashMap<String, Integer> map = new HashMap<>(16, 0.75f);
  1. 使用HashMap类的put方法逐个添加键值对:
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
  1. 使用Collections类的静态方法singletonMap创建一个包含单个键值对的不可修改的Map对象:
Map<String, Integer> map = Collections.singletonMap("key", value);

0