-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap.java
More file actions
104 lines (85 loc) · 1.97 KB
/
HashMap.java
File metadata and controls
104 lines (85 loc) · 1.97 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
104
package ds;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Standard representation of a HashMap. Should add resize method.
*
* @author shivam.maharshi
*
* @param <K>
* @param <V>
*/
public class HashMap<K, V> {
int size;
LinkedList<Entry<K, V>>[] hashArray;
@SuppressWarnings("unchecked")
public HashMap(int capacity) {
hashArray = new LinkedList[capacity];
}
public void add(K key, V value) {
int hash = getHash(key);
LinkedList<Entry<K, V>> list = hashArray[hash];
if (list != null) {
list = new LinkedList<Entry<K, V>>();
}
Entry<K, V> entry = new Entry<K, V>(key, value);
list.add(entry);
}
public V get(K key) {
int hash = getHash(key);
LinkedList<Entry<K, V>> list = hashArray[hash];
if (list != null) {
return fetchValueFromList(key, list);
}
return null;
}
public void delete(K key) {
int hash = getHash(key);
LinkedList<Entry<K, V>> list = hashArray[hash];
if (list != null) {
deleteEntryFromList(key, list);
}
}
private V fetchValueFromList(K key, LinkedList<Entry<K, V>> list) {
Iterator<Entry<K, V>> it = list.iterator();
while (it.hasNext()) {
Entry<K, V> entry = it.next();
if (entry.getKey().equals(key)) {
return entry.getValue();
}
}
return null;
}
private void deleteEntryFromList(K key, LinkedList<Entry<K, V>> list) {
Iterator<Entry<K, V>> it = list.iterator();
while (it.hasNext()) {
Entry<K, V> entry = it.next();
if (entry.getKey().equals(key)) {
list.remove(entry);
}
}
}
private int getHash(K key) {
return key.hashCode();
}
}
class Entry<K, V> {
private K key;
private V value;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}