-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.java
73 lines (56 loc) · 1.5 KB
/
HashTable.java
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
public class HashTable {
LinkedList[] values;
int load;
public HashTable() {
values = createArray(16);
load = 0;
}
private int hash(String str) {
int hash = 0;
final int prime = 31;
for (int i = 0; i < str.length(); i++) {
hash = prime * hash + str.charAt(i);
}
return Math.abs(hash % values.length);
}
public void put(String str) {
int index = hash(str);
if (load > (values.length * .75)) {
grow();
}
if (values[index].add(str)) {
load++;
}
}
private void grow() {
LinkedList[] temp = createArray(values.length * 2);
for (LinkedList list : values) {
for (int i = 0; i < list.size(); i++) {
temp[hash(list.get(i))].add(list.get(i));
}
}
values = temp;
}
public boolean contains(String val) {
if (values[hash(val)].contains(val) != -1) {
return true;
}
return false;
}
public boolean remove(String str) {
load--;
return values[hash(str)].removeFirst(str);
}
private LinkedList[] createArray(int l) {
LinkedList[] temp = new LinkedList[l];
for (int i = 0; i < l; i++) {
temp[i] = new LinkedList();
}
return temp;
}
public void printInOrder() {
for (LinkedList list : values) {
list.print();
}
}
}