java清空map的方法是什么

小億
270
2023-09-16 09:44:25

要清空一個(gè)Java的Map,可以使用以下兩種方法:

  1. 使用Map的clear()方法:使用該方法將Map中的所有鍵值對(duì)清除。

示例代碼:

Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.clear(); // 清空Map
System.out.println(map); // 輸出: {}
  1. 創(chuàng)建一個(gè)新的空的Map對(duì)象賦值給原來的Map變量:通過重新賦值一個(gè)空的Map對(duì)象,原來的Map對(duì)象中的鍵值對(duì)將被垃圾回收清除。

示例代碼:

Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map = new HashMap<>(); // 清空Map
System.out.println(map); // 輸出: {}

以上兩種方法都可以清空一個(gè)Map,選擇使用哪種方法取決于具體的需求和代碼的結(jié)構(gòu)。

0