-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashTable.java
68 lines (54 loc) · 1.35 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
package com.faisal;
import java.util.LinkedList;
public class HashTable {
private class Entry {
private int key;
private String value;
public Entry(int key, String value) {
this.key = key;
this.value = value;
}
}
private LinkedList<Entry>[] entries = new LinkedList[5];
public void put(int key, String value) {
var entry = getEntry(key);
if (entry != null) {
entry.value = value;
return;
}
getOrCreateBucket(key).add(new Entry(key, value));
}
public String get(int key) {
var entry = getEntry(key);
return (entry == null) ? null : entry.value;
}
public void remove(int key) {
var entry = getEntry(key);
if (entry == null)
throw new IllegalStateException();
getBucket(key).remove(entry);
}
private LinkedList<Entry> getBucket(int key) {
return entries[hash(key)];
}
private LinkedList<Entry> getOrCreateBucket(int key) {
var index = hash(key);
var bucket = entries[index];
if (bucket == null)
entries[index] = new LinkedList<>();
return bucket;
}
private Entry getEntry(int key) {
var bucket = getBucket(key);
if (bucket != null) {
for (var entry : bucket) {
if (entry.key == key)
return entry;
}
}
return null;
}
private int hash(int key) {
return key % entries.length;
}
}