-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.java
More file actions
103 lines (82 loc) · 2.54 KB
/
HashTable.java
File metadata and controls
103 lines (82 loc) · 2.54 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
package net.reservoircode.structures;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.lang.String.format;
import static java.util.Objects.isNull;
public class HashTable<T> {
private static final int DEFAULT_SIZE = 4;
private final int size;
private final Logger logger;
private final Entry<T>[] entries;
private int count = 0;
public HashTable() {
this(DEFAULT_SIZE);
}
public HashTable(int size) {
this(size, LoggerFactory.getLogger(HashTable.class));
}
/* visible for testing */ HashTable(int size, Logger logger) {
if (size < 1) {
throw new IllegalStateException(format("Invalid size provided: %s", size));
}
this.size = size;
this.logger = logger;
logger.debug("Creating hashtable with size: {}", size);
entries = new Entry[this.size];
}
public void put(String key, T value) {
if (isNull(key)) {
throw new IllegalArgumentException("Key must not be null");
}
Entry<T> entry = new Entry<>(key, value);
count++;
int position = hash(key) % size;
if (entries[position] == null) {
entries[position] = entry;
} else {
logger.debug("Collision when putting key: {}", key);
Entry<T> current = entries[position];
while (current.next != null) {
current = current.next;
}
current.next = entry;
}
}
public T get(String key) {
if (isNull(key)) {
throw new IllegalArgumentException("Key must not be null");
}
int position = hash(key) % size;
Entry<T> current = entries[position];
if (entries[position] == null) {
return null;
}
if (current.key.equals(key)) {
return current.value;
}
logger.debug("Collision when getting key: {}", key);
while (current.next != null) {
if (current.next.key.equals(key)) {
return current.next.value;
}
current = current.next;
}
return null;
}
public int count() {
return count;
}
public int hash(String key) {
return key.hashCode();
}
private static class Entry<T> {
private final String key;
private final T value;
private Entry<T> next;
public Entry(String key, T value) {
this.key = key;
this.value = value;
this.next = null;
}
}
}