当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java ConcurrentHashMap clear()用法及代码示例


先决条件:Java并发哈希图

clear()方法
java.util.concurrentHashMap.clear()方法用于清除映射。它用于从ConcurrentHashMap中删除映射。

用法:


public void clear()
// Java program to demonstrate 
// clear() method 
  
import java.util.concurrent.ConcurrentHashMap; 
import java.util.*; 
  
public class ConcurrentHashMapExample { 
  
    public static void main(String[] args) 
    { 
  
        // Creating a ConcurrentHashMap 
        Map<String, String> my_cmmap = new ConcurrentHashMap<String, String>(); 
  
        // Inserting mappings in ConcurrentHashMap 
        // with the help of put() method 
        my_cmmap.put("1", "1"); 
        my_cmmap.put("2", "1"); 
        my_cmmap.put("3", "1"); 
        my_cmmap.put("4", "1"); 
        my_cmmap.put("5", "1"); 
        my_cmmap.put("6", "1"); 
  
        // Print the ConcurrentHashMap 
        System.out.println("Map before use of clear():\n"
                           + my_cmmap); 
  
        // Now clear the map using clear() 
        my_cmmap.clear(); 
  
        // Print the clea Map 
        System.out.println("Map after use of clear():"
                           + my_cmmap); 
    } 
}
输出:
Map before use of clear():
{1=1, 2=1, 3=1, 4=1, 5=1, 6=1}
Map after use of clear():{}

范例2:

// Java program to demonstrate 
// clear() method 
  
import java.util.concurrent.ConcurrentHashMap; 
import java.util.*; 
  
public class ConcurrentHashMapExample { 
  
    public static void main(String[] args) 
    { 
        // Creating a ConcurrentHashMap 
        Map<String, String> my_map = new ConcurrentHashMap<String, String>(); 
  
        // Inserting mappings in ConcurrentHashMap 
        // with the help of put() method 
        my_map.put("Geeks", "100"); 
        my_map.put("Geek2", "150"); 
        my_map.put("Geeks3", "120"); 
        my_map.put("Geek4", "111"); 
        my_map.put("Geek5", "110"); 
        my_map.put("Geek6", "100"); 
  
        // Print the ConcurrentHashMap 
        System.out.println("Map before use of clear():\n"
                           + my_map); 
  
        // Now clear the map using clear() 
        my_map.clear(); 
  
        // Print the cleared Map 
        System.out.println("Map after use of clear():"
                           + my_map); 
    } 
}
输出:
Map before use of clear():
{Geeks3=120, Geek6=100, Geek5=110, Geek4=111, Geeks=100, Geek2=150}
Map after use of clear():{}


相关用法


注:本文由纯净天空筛选整理自barykrg大神的英文原创作品 Java ConcurrentHashMap | clear()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。