-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHashTable.java
More file actions
99 lines (77 loc) · 2.39 KB
/
HashTable.java
File metadata and controls
99 lines (77 loc) · 2.39 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
import java.util.LinkedList;
public class HashTable {
public static final int ARR_SIZE = 8;
public LinkedList<Bucket>[] arr = new LinkedList[ARR_SIZE];
//hash function
public int getIndexBelowMaxForKey(String str, int max) {
int hash = 0;
for (int i = 0; i < str.length(); i++) {
hash = (hash << 5) + hash + str.charAt(i);
hash = hash & hash; // Convert to 32bit integer
hash = Math.abs(hash);
}
return hash % max;
}
public static class Bucket {
public String key;
public String value;
}
public void insert (String key, String value) {
int index = getIndexBelowMaxForKey(key, ARR_SIZE);
LinkedList<Bucket> items = arr[index];
if(items == null) {
items = new LinkedList<Bucket>();
Bucket item = new Bucket();
item.key = key;
item.value = value;
items.add(item);
arr[index] = items;
}
else {
for(Bucket item : items) {
if(item.key.equals(key)) {
item.value = value;
return;
}
}
Bucket item = new Bucket();
item.key = key;
item.value = value;
items.add(item);
}
}
private String retrieve(String key) {
if(key == null)
return null;
int index = getIndexBelowMaxForKey(key, ARR_SIZE);
LinkedList<Bucket> items = arr[index];
if(items == null)
return null;
for(Bucket item : items) {
if(item.key.equals(key))
return item.value;
}
return null;
}
public void remove (String key) {
int index = getIndexBelowMaxForKey(key, ARR_SIZE);
LinkedList<Bucket> items = arr[index];
if(items == null)
return;
for(Bucket item : items) {
if (item.key.equals(key)) {
items.remove(item);
return;
}
}
}
public static void main(String[] args) {
HashTable hashTable = new HashTable();
// Put some key values.
hashTable.insert("cat","1");
hashTable.insert("cat","2");
hashTable.insert("dog","3");
hashTable.remove("cat");
System.out.println(hashTable.retrieve("dog"));
}
}