java - HashMap(Map m) 构造函数的作用是什么?

标签 java hashmap

我发现了一段代码

  public class MapImpl {
   private static MapImpl mpl = new MapImpl();
     Map<String,String> hm;
     private MapImpl() {
          hm = new HashMap<>();
       }
     public addContentsToMap(Map<String,String> m){
         this.hm=m;
     }
     public Map returnMap(){
         new HashMap<>(hm);
       }
    }

我想知道,当调用默认构造函数时,映射会初始化为 hashmap,而当调用 addContentsToMap 时,映射会由值形成。

我看到returnMap使用了HashMap(Map m)的构造函数。我浏览了HashMap的源代码,但一无所知。

最佳答案

它需要 Map 的任何实现接口(interface)并构造一个 HashMap这也是 Map 的实现界面。

开发人员喜欢 Hash-Collections( HashSetHashMap 等),包括 HashMap因为他们提供了预期的 O(1)获取并包含时间。

一旦您拥有Map,它就会很有用。这不是HashMap (例如 Properties )并且您知道它会很大并且您会多次读取它,切换到 Map 的不同实现很有用。 .

Documentation:

public HashMap(Map<? extends K,? extends V> m)

Constructs a new HashMap with the same mappings as the specified Map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.

Parameters:

m - the map whose mappings are to be placed in this map

Throws:

NullPointerException - if the specified map is null

关于java - HashMap(Map m) 构造函数的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45795833/

相关文章:

kotlin - 在 Kotlin 中有效地查看(或复制)大型 HashMap 的子集

java - 使用 hashmap 表示加权图

java - 为什么在 HashMap 中找不到 key ?

java - 遍历 hashmap - 抛出异常

java - 如何获取列表中数字出现的频率

java - 从restTemplate 映射到Map<String, Integer>

Java Mail 正在显示 <h2> 文本

java - RabbitMQ Spring 死信配置不起作用

java - 没有服务器响应的 SSL 握手与 java 1.8

C映射数据结构