在上一篇教程中,我们分享了如何根据键从HashMap中删除特定的映射。在这个例子中,我们将看到如何从HashMap中删除所有映射。我们将使用HashMap类的clear()方法来做到这一点:
public void clear():从此映射中删除所有映射。此调用返回后,映射将为空。
完整代码:
import java.util.HashMap;public class RemoveAllExample { public static void main(String[] args) { // Creating a HashMap of int keys and String values HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); // Adding Key and Value pairs to HashMap hashmap.put(11,"Value1"); hashmap.put(22,"Value2"); hashmap.put(33,"Value3"); hashmap.put(44,"Value4"); hashmap.put(55,"Value5"); // Displaying HashMap Elements System.out.println("HashMap Elements: " + hashmap); // Removing all Mapping hashmap.clear(); // Displaying HashMap Elements after remove System.out.println("After calling clear():"); System.out.println("---------------------"); System.out.println("HashMap Elements: " + hashmap); }}
输出:
HashMap Elements: {33=Value3, 55=Value5, 22=Value2, 11=Value1, 44=Value4}After calling clear():---------------------HashMap Elements: {}正如您所看到的,在调用clear()方法之后,HashMap的所有映射都已被删除,之后HashMap变为空。
