Repository navigation
Expand file tree
/
Copy pathHashTable.java
More file actions
111 lines (91 loc) · 2.98 KB
/
Copy pathHashTable.java
File metadata and controls
111 lines (91 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package datastructures;
public class HashTable {
private int INITIAL_SIZE = 16;
private HashEntry[] data; // LinkedList
class HashEntry {
String key;
String value;
HashEntry next;
HashEntry(String key, String value) {
this.key = key;
this.value = value;
this.next = null;
}
}
HashTable() {
data = new HashEntry[INITIAL_SIZE];
}
public void put(String key, String value) {
// Get the index
int index = getIndex(key);
// Create the linked list entry
HashEntry entry = new HashEntry(key, value);
// If no entry there - add it
if (data[index] == null) {
data[index] = entry;
}
// Else handle collision by adding to end of linked list
else {
HashEntry entries = data[index];
// Walk to the end...
while(entries.next != null) {
entries = entries.next;
}
// Add our new entry there
entries.next = entry;
}
}
public String get(String key) {
// Get the index
int index = getIndex(key);
// Get the current list of entries
HashEntry entries = data[index];
// if we have existing entries against this key...
if (entries != null) {
// else walk chain until find a match
while (!entries.key.equals(key) && entries.next !=null) {
entries = entries.next;
}
// then return it
return entries.value;
}
// it we have no entries against this key...
return null;
}
private int getIndex(String key) {
// Get the hash code
int hashCode = key.hashCode();
System.out.println("hashCode = " + hashCode);
// Convert to index
int index = (hashCode & 0x7fffffff) % INITIAL_SIZE;
// int index = hashCode % INITIAL_SIZE;
// Hack to force collision for testing
if (key.equals("John Smith") || key.equals("Sandra Dee")) {
index = 4;
}
System.out.println("index = " + index);
return index;
}
@Override
public String toString() {
int bucket = 0;
StringBuilder hashTableStr = new StringBuilder();
for (HashEntry entry : data) {
if(entry == null) {
continue;
}
hashTableStr.append("\n bucket[")
.append(bucket)
.append("] = ")
.append(entry.toString());
bucket++;
HashEntry temp = entry.next;
while(temp != null) {
hashTableStr.append(" -> ");
hashTableStr.append(temp.toString());
temp = temp.next;
}
}
return hashTableStr.toString();
}
}