hashmap初始化的方式有哪些

小億
160
2024-03-11 14:55:24

  1. 使用HashMap類的構(gòu)造方法創(chuàng)建一個(gè)空的HashMap對(duì)象:
HashMap<String, Integer> map = new HashMap<>();
  1. 使用HashMap類的構(gòu)造方法創(chuàng)建一個(gè)包含指定初始容量和負(fù)載因子的HashMap對(duì)象:
HashMap<String, Integer> map = new HashMap<>(16, 0.75f);
  1. 使用HashMap類的put方法逐個(gè)添加鍵值對(duì):
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
  1. 使用Collections類的靜態(tài)方法singletonMap創(chuàng)建一個(gè)包含單個(gè)鍵值對(duì)的不可修改的Map對(duì)象:
Map<String, Integer> map = Collections.singletonMap("key", value);

0