Java LinkedHashMap clear()方法

Java LinkedHashMap clear()方法

java.util.LinkedHashMap.clear()是Java中LinkedHashMap类的一个内置方法,用于清除所有的元素或指定的LinkedHashMap中的映射。在执行该操作后,该地图将变成空的。

语法

Linked_Hash_Map.clear()

参数: 该方法不接受任何参数。

返回值: 该方法不返回任何值。

下面的程序说明了java.util.LinkedHashMap.clear()方法:

程序1: 将字符串值映射到整数键。

// Java code to illustrate the clear() method
import java.util.*;
  
public class Linked_Hash_Map_Demo {
    public static void main(String[] args)
    {
        // Creating an empty LinkedHashMap
        LinkedHashMap<Integer, String> li_hash_map =
        new LinkedHashMap<Integer, String>();
  
        // Mapping string values to int keys
        li_hash_map.put(10, "Geeks");
        li_hash_map.put(15, "4");
        li_hash_map.put(20, "Geeks");
        li_hash_map.put(25, "Welcomes");
        li_hash_map.put(30, "You");
  
        // Displaying the LinkedHashMap
        System.out.println("Initial Mappings are: " + li_hash_map);
  
        // Clearing the linked hash map using clear()
        li_hash_map.clear();
  
        // Displaying the final HashMap
        System.out.println("Finally the maps look like this: " + li_hash_map);
    }
}

输出:

Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
Finally the maps look like this: {}

程序2: 将整数值映射到字符串键。

// Java code to illustrate the clear() method
import java.util.*;
  
public class Linked_Hash_Map_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty LinkedHashMap
        LinkedHashMap<String, Integer> li_hash_map =
        new LinkedHashMap<String, Integer>();
  
        // Mapping int values to string keys
        li_hash_map.put("Geeks", 10);
        li_hash_map.put("4", 15);
        li_hash_map.put("Geeks", 20);
        li_hash_map.put("Welcomes", 25);
        li_hash_map.put("You", 30);
  
        // Displaying the LinkedHashMap
        System.out.println("Initial Mappings are: " + li_hash_map);
  
        // Clearing the linked hash map using clear()
        li_hash_map.clear();
  
        // Displaying the final HashMap
        System.out.println("Finally the maps look like this: " + li_hash_map);
    }
}

输出:

Initial Mappings are: {Geeks=20, 4=15, Welcomes=25, You=30}
Finally the maps look like this: {}

注意: 同样的操作可以通过不同数据类型的变化和组合对任何类型的Mapping进行操作。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程