Integer itr = Integer.valueOf(17683);
itr.hashCode();
// Output: 17683
String str = new String("17683");
str.hashCode();
// Output: s.charAt(0) * 31^(n-1) + s.charAt(1) * 31^(n-2) + ... + s.charAt(n-1)
cats
is $327^3 + 127^2 + 2027^1 + 1927^0$cats
is $9931^3 + 9731^2 + 11631^1 + 11531^0$A-Z (65-90), a-z (97-122)
The fifth bit indicates lowercase
B
(ASCII 66) is 01000010
in binary.b
(ASCII 98) is 01100010
in binary.In the English articles, there are more lowercase letters than uppercase letters
ab
is $97 * 32 + 98$97 * 32 + 98
= 97 << 5 + 98
Prbability of fifth bit is not spreaded:
110000100000 --> 97 << 5
+ 1100010 --> 98
△△
------------
110010000010
ab
is $97 * 31 + 98$
Since $32 = 2^5$, perform 97 * 31 + 98
= 97 << 5 - 97 + 98
Spreading out the bits:
110000100000 --> 97 << 5
- 1100001 --> 97
△
----------------
101110111111
+ 1100010 --> 98
----------------
110000100001
In Java 7's HashMap:
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
static int indexFor(int h, int length) {
return h & (length - 1);
}
Reason:
Example:
1010110 <- 86
AND 0000111 <- 7
----------
0000110 <- 6
Drawbacks:
int hash = hash(key.hashCode());
Map<String, Integer> freqOfWords = new HashMap<String, Integer>(10, 0.65f);
String[] words = "coming together is a beginning keeping together is progress working together is success"
.split(" ");
for (String word : words) {
Integer frequency = freqOfWords.get(word);
if (frequency == null) {
frequency = 1;
} else {
frequency++;
}
freqOfWords.put(word, frequency);
}
Iterator<String> itr = freqOfWords.keySet().iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println();
// using enhanced for-loop and keySet method
for (String word : freqOfWords.keySet()) {
System.out.println(word);
}
System.out.println();
// using enhanced for-loop and values method
for (Integer frequency : freqOfWords.values()) {
System.out.println(frequency);
}
Use of dummy object seems a waste of memory?
public class HashSet<E> implements Set<E> {
private ... HashMap<E, Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
}
Set<String> distinctWords = new HashSet<String>();
String[] words = "coming together is a beginning keeping together is progress working together is success"
.split(" ");
for (String word : words) {
// No duplicate is allowed
distinctWords.add(word);
}