1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't mean to compare, I was wondering if there is any drop in performance due to the length of string.
Yes. You can even see the code for String.hashCode() in your eclipse and see the loop. (see edit in my answer)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.