-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashtable.java
More file actions
111 lines (92 loc) · 2.46 KB
/
Hashtable.java
File metadata and controls
111 lines (92 loc) · 2.46 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
import java.util.Arrays;
public class Hashtable<k, v> {
private HashNode<k, v>[] table;
private int items;
private final double LAMBDA = 0.75;
public Hashtable() {
table = new HashNode[50];
}
private int getSlot(String key) {
int slot = key.hashCode();
slot = Math.abs(slot % table.length); //to avoid negative hashes
return slot;
}
boolean containsKey (String key) {
for(int i = 0; i < table.length; i++) { // linear probing
if(table[i] != null) {
if(table[i].deleted = false && table[i].getKey() == key) {
return true;
}
}
}
return false;
}
String get (String key) {
int slot = getSlot(key);
HashNode node = table[slot];
while(node != null && key != node.getKey()) {
// node = node.getNext;
slot = (slot + 1) % table.length;
node = table[slot];
}
if(node != null) {
return node.getValue();
}
else {
return null;
}
}
void put (String key, String value) {
int slot = getSlot(key);
while(table[slot] != null && table[slot].getKey() != key){ // avoid duplicate entries
slot = (slot + 1) % table.length;
}
table[slot] = new HashNode(key, value);
++items;
if(items/table.length >= LAMBDA) {
growSize();
}
}
String remove (String key) {
int slot = getSlot(key);
for(int i = 0; i < table.length; i++) { // probing
int newSlot = (slot + (i * i)) % table.length; // quadratic
HashNode node = table[newSlot];
if(node.getKey() == key) {
node.setDelete(true);
items--;
return node.getValue();
}
}
return null;
}
private void growSize() {
table = Arrays.copyOf(table, table.length * 2);
}
}
class HashNode<k, v> {
String key;
String value;
boolean deleted;
public HashNode(String k, String v) {
key = k;
value = v;
}
//accessors
public String getKey() {
return key;
}
public String getValue() {
return value;
}
//mutators
public void setKey(String k) {
key = k;
}
public void setValue(String v) {
value = v;
}
public void setDelete(boolean state) {
deleted = state;
}
}