-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.java
More file actions
105 lines (91 loc) · 2.07 KB
/
Copy pathHashTable.java
File metadata and controls
105 lines (91 loc) · 2.07 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
public class HashTable {
private class Entry {
String key;
String value;
Entry next;
public Entry(String key, String value) {
this.key = key;
this.value = value;
}
}
private int TABLE_SIZE;
private int size;
private Entry[] table;
public HashTable(int ts) {
size = 0;
TABLE_SIZE = ts;
table = new Entry[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = null;
}
public int getSize() {
return size;
}
public boolean makeEmpty() {
for (int i = 0; i < table.length; i++) {
table[i] = null;
}
return true;
}
public String get(String key) {
int hashIndex = myhash(key);
if (table[hashIndex] == null) {
return null;
} else {
Entry entry = table[hashIndex];
while (entry != null && !entry.key.equals(key))
entry = entry.next;
if (entry.key.equals(key))
return entry.value;
else
return null;
}
}
public void insert(String key, String value) {
int hashIndex = myhash(key);
if (table[hashIndex] == null) {
Entry entry = new Entry(key, value);
table[hashIndex] = entry;
} else {
Entry entry = table[hashIndex];
while (entry.next != null && !entry.key.equals(key))
entry = entry.next;
if (entry.key.equals(key))
entry.value = value;
else
entry.next = new Entry(key, value);
}
size++;
}
public boolean remove(String key) {
int hashIndex = myhash(key);
if(table[hashIndex] == null) {
return false;
} else {
Entry previous = null;
Entry current = table[hashIndex];
while(current != null && !current.key.equals(key)) {
previous = current;
current = current.next;
}
if(current.key.equals(key)) {
if(previous == null) {
table[hashIndex] = current.next;
} else {
previous.next = current.next;
}
size--;
return true;
} else {
return false;
}
}
}
private int myhash(String x) {
int hashVal = x.hashCode();
hashVal %= TABLE_SIZE;
if (hashVal < 0)
hashVal += TABLE_SIZE;
return hashVal;
}
}