Dhruv Mullick
Dhruv Mullick

Reputation: 561

What is the time complexity for adding a String,String entry to a HashMap in Java?

If we have a HashMap<String,String> H, and we use the code H.put("Hello","World"). Would the time complexity be the same as in the case where we use an integer key-value pair in a HashMap? I feel that the performance with String should be poorer, as hashing the String would be an O(String length) operation.

Upvotes: 1

Views: 538

Answers (1)

Yossi Vainshtein
Yossi Vainshtein

Reputation: 3985

Yes, It's performance will be poorer since hashing a string is indeed slower then hashing an integer.

In fact, Java uses a specific formula for hashCode() of String, which you can see here, and it does check all the charachters of the string, as you would expect.

In my Eclipse the code for hashCode():

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

        for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
}

But why are you comparing these two things? It doesn't make much sense to compare complexity of two algorithms which do different things.

Upvotes: 2

Related Questions