我只是在解决leetcode https://leetcode.com/problems/insert-delete-getrandom-o1/submissions/上的一些问题,在使用arraylist.size()和HashMap.size()函数时,我观察到执行时间急剧增加(从14毫秒到248毫秒)是总体解决方案,因此我想知道HashMap到底是如何计算其大小的?
我还没有定义这两个集合的初始容量。
查看Java文档:https://docs.oracle.com/javase/6/docs/api/java/util/hashmap.html
和https://www.linkedin.com/pulse/10-things--developer-shoul-know-hashmap-chinmay-parekh->; 第3,4号
检查它的简单方法是编写简单的代码块:
HashMap<String, String> map = new HashMap<>();
map.put("A", "B");
map.remove("A");
System.out.println(map.size());
按Ctrl
,然后单击相关方法查看它们的实现。 size()
方法基本上是返回实例变量的getter
方法; transient
integer表示映射中键的计数。 当您成功地将元素添加到映射中/从映射中删除元素时,大小将在相关方法内部更改:
大小():
transient int size;
public int size() {
return this.size;
}
放(k,v):
final V putVal(parameters..) {
// some stuff
++this.modCount;
if (++this.size > this.threshold) {
this.resize();
}
// some others
}
删除(对象):
final HashMap.Node<K, V> removeNode(parameters..) {
// some stuff
++this.modCount;
--this.size;
// some others
}
hashmap.size()
方法返回size
成员变量的值。 如果您不能在本地访问完整的源代码,可以在GitHub上找到它:https://github.com/openjdk/jdk/blob/bc822ffad8d69792a093a98c7244311da5eef625/src/Java.base/share/类/Java/util/hashmap.Java#l526
/**
* Returns the number of key-value mappings in this map.
*
* @return the number of key-value mappings in this map
*/
public int size() {
return size;
}
您看到的“执行时间剧增”可能是因为HashMap是比ArrayList更复杂的数据结构。 这意味着像添加或查找值这样的操作会有更多的开销。