678 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

2 Answers

Best answer
6 votes
6 votes

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
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

2 votes
2 votes
2 answers
4
Bikram asked Oct 4, 2016
347 views
$$T(n) = \begin{cases} 4 & \quad if \: \: n =1 \\ T(n-1) + 4 & \quad otherwise \end{cases}$$Value of $T(1000)$ is ___