[英]Complexity of java hashmap for hash of string
I was looking at java source code in HashMap class. 我在看HashMap类中的Java源代码。
final int hash(Object k) {
int h = 0;
if (useAltHashing) {
if (k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h = hashSeed;
}
h ^= k.hashCode();
So, what is the time complexity of hashmapObject.put("somestring") ? 那么,hashmapObject.put(“ somestring”)的时间复杂度是多少? Is it O(1) or O(n) where n is number of characters in a string.
是O(1)还是O(n),其中n是字符串中的字符数。
In worst case time(In practise it happens rarely , only when we have a bad hashing function) complexity for put
method in hashmap is O(N)
, because although we add the element at the beginning of the linked list( O(1)
) but we still need to loop through the bucket(linked list) to determine if that new element already exists or not. 在最坏的情况下(实际上,只有当哈希函数不好时,这种情况很少发生),哈希映射中
put
方法的复杂度为O(N)
,因为尽管我们在链表的开头添加了元素( O(1)
),但我们仍然需要遍历bucket(链接列表)以确定该新元素是否已经存在。
Updated: As per Peter Lawery comment in java 8 its O(log n)
. 更新:根据Peter Lawery在Java 8中的注释,其
O(log n)
。 This optimization is described here but in a nutshell an ad-hoc implementation of tree map is used as a bucket when the size of the bucket crosses the threshold value. 这里描述了这种优化,但是简而言之,当存储桶的大小超过阈值时,树形图的即席实现用作存储桶。 The threshold value is setted by the variable
static final int TREEIFY_THRESHOLD = 8;
阈值由变量
static final int TREEIFY_THRESHOLD = 8;
in HashMap.java
在
HashMap.java
It is O(1) wrt the size of the map, which is what is usually of interest. 它通常是地图的大小的O(1) 。 It is O(N) wrt the length of the string.
字符串的长度为O(N) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.