Reputation: 561
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
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