简体   繁体   中英

Complexity of java hashmap for hash of string

I was looking at java source code in HashMap class.

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") ? Is it O(1) or O(n) where n is number of characters in a string.

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.
Updated: As per Peter Lawery comment in java 8 its 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; in HashMap.java

It is O(1) wrt the size of the map, which is what is usually of interest. It is O(N) wrt the length of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM