-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.java
More file actions
93 lines (69 loc) · 2.28 KB
/
HashTable.java
File metadata and controls
93 lines (69 loc) · 2.28 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
class HashTable<K, V> {
private static final int SIZE = 10;
private final HashEntry[] entries = new HashEntry[SIZE];
//Not an inner class, top-level class and do not need an instance of enclosing class.
//Can be declared public, protected, default, private
//Can access only the static members of the outer class.
private static class HashEntry<K, V> {
K key;
V value;
HashEntry<K, V> next;
HashEntry(K k, V v) {
this.key = k;
this.value = v;
this.next = null;
}
@Override
public String toString() {
return "HashEntry{" + "key=" + key + ", value=" + value + ", next=" + next + '}';
}
}
public V put(K key, V value) {
int hash = getHash(key);
final HashEntry hashEntry = new HashEntry(key, value);
if (entries[hash] == null) {
entries[hash] = hashEntry;
} else {
HashEntry currentEntry = entries[hash];
while (currentEntry != null) {
if (currentEntry.key.equals(key)) {
currentEntry.value = value;
return (V) currentEntry;
} else {
currentEntry = currentEntry.next;
}
}
currentEntry.next = hashEntry;
}
return (V) hashEntry;
}
public V get(K key) {
int hash = getHash(key);
if (entries[hash] != null) {
HashEntry currentEntry = entries[hash];
while (currentEntry != null) {
if (currentEntry.key.equals(key)) {
return (V) currentEntry.value;
}
currentEntry = currentEntry.next;
}
}
return null;
}
private int getHash(K key) {
return Math.abs(key.hashCode() % SIZE);
}
public int getKeyEntriesCount(K key) {
int count = 1;
int hash = getHash(key);
HashEntry<K, V> currentEntry = entries[hash];
if (currentEntry == null) {
return 0; // No entries found.
}
while (Objects.nonNull(currentEntry.next)) {
currentEntry = currentEntry.next;
count++;
}
return count;
}
}