Hash function should:
Helpful to consider 1-2 separately from 3
code % table_sizeLet's look at some hash code functions from Java...
@Override
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
https://github.com/openjdk/jdk17/blob/master/src/java.base/share/classes/java/lang/Integer.java
Javadoc:
"Returns a hash code for this string. The hash code for a String object is computed as int arithmetic, where s[i] is the n is the length of the string. (The hash value of the empty string is zero.)"
public int hashCode() {
int h = hash;
if (h == 0 && !hashIsZero) {
h = isLatin1() ? StringLatin1.hashCode(value)
: StringUTF16.hashCode(value);
if (h == 0) {
hashIsZero = true;
} else {
hash = h;
}
}
return h;
}
https://github.com/openjdk/jdk17/blob/master/src/java.base/share/classes/java/lang/String.java
public static int hashCode(byte[] value) {
int h = 0;
int length = value.length >> 1;
for (int i = 0; i < length; i++) {
h = 31 * h + getChar(value, i);
}
return h;
}
https://github.com/openjdk/jdk17/blob/master/src/java.base/share/classes/java/lang/StringUTF16.java
Does the String hashCode method guarantee that no two strings will hash to the same value? If not, is it possible to design a hashCode method that would have this property?
A) Yes
B) No, Yes
C) No, No
Worst case insertion time?
Load factor:
Question: what is the average number of comparisons required to find a key in a table with the load factor
As long as
How can
hashCode method from Java.hashCode.)What is the relationship between the equals method and the hashCode method in Java?
A) Any time the equals method is overriden, hashCode should be as well. Hashing will break if two non-equal objects can have the same hash code.
B) Any time the equals method is overriden, hashCode should be as well. Hashing will break if two equal objects can have different hash codes.
C) Any time the equals method is overriden, hashCode should be as well. Hashing will be slow if two non-equal objects can have the same hash code.
D) Any time the equals method is overriden, hashCode should be as well. Hashing will be slow if two equal objects can have different hash codes.
D) There is no real relationship between equals and hashCode. It is fine to override one without considering the other.