in Algorithms
379 views
3 votes
3 votes

Is the following implementation of hashCode() legal assming a hashtable of size 20?

public int hashCode(x) {
    return 17;
}
  1. yes
  2. no because it fills only one slot
  3. no because it does not ensure uniform filling
  4. no because the hashcode is independent of the key
in Algorithms
by
379 views

2 Answers

6 votes
6 votes
Best answer

Yes, offcourse it is legal and question asks only that it is legal or not. But, it is very less efficient as all the elements will be forwarded to only one slot 17. Hence, when there are N elements, all are forwarded to same slot and we have to search the element in this slot, which will be very less efficient. 

So, it is always better to use key value to forward a particular element into a particular slot .

This is better => 

public int hashCode(x) {
    return (x + 7);
}
selected by
by

4 Comments

return  (x+7)%20  instead of (x+7)
3
3
but hash code is always dependent on key value. is it not contradict with defination of hashing ?
0
0
2
2
why x+7
0
0
0 votes
0 votes

Legal means there would be no compile-time, or run-time errors (and/or warnings?).

Yes, this code is syntactically correct. Terrible implementation, but perfectly legal. 

Option A.

Answer:

Related questions