我发现了一段代码
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( HashSet
、 HashMap
等),包括 HashMap
因为他们提供了预期的 O(1)
获取并包含时间。
一旦您拥有Map
,它就会很有用。这不是HashMap
(例如 Properties
)并且您知道它会很大并且您会多次读取它,切换到 Map
的不同实现很有用。 .
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 mapThrows:
NullPointerException
- if the specified map is null
关于java - HashMap(Map m) 构造函数的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45795833/