-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyObject.java
More file actions
64 lines (53 loc) · 1.44 KB
/
Copy pathMyObject.java
File metadata and controls
64 lines (53 loc) · 1.44 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
package project1;
/*
we store data in a way that we match some key to some value
used like frequency arrays
and some more complex examples
like storing an array of indecies as a value for substring
*/
public class MyObject<K, V> {
private static class Entry<K, V> {
K key;
V value;
Entry<K, V> next;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
private Entry<K, V>[] array_of_entries;
private int size = 20;
public MyObject() {
this.array_of_entries = new Entry[size];
}
private int getPos(K key) {
if (key == null) return 0;
return Math.abs(key.hashCode()) % size; // how the key is hashed in the memory
}
public void set(K key, V value) {
int idx = getPos(key);
Entry<K, V> headEntry = array_of_entries[idx];
while (headEntry != null) {
if (headEntry.key.equals(key)) { // search for key like we do in LinkedList
headEntry.value = value;
return;
}
headEntry = headEntry.next;
}
// if not found
Entry<K, V> newEntry = new Entry<>(key, value);
newEntry.next = array_of_entries[idx];
array_of_entries[idx] = newEntry;
}
public V get(K key) {
int idx = getPos(key);
Entry<K, V> headEntry = array_of_entries[idx];
while (headEntry != null) {
if (headEntry.key.equals(key)) {
return headEntry.value;
}
headEntry = headEntry.next;
}
return null;
}
}