-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHashMap.java
112 lines (100 loc) · 3.12 KB
/
HashMap.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
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
105
106
107
108
109
110
111
112
import java.util.ArrayList;
class HashNode<K,V> {
K key;
V value;
HashNode<K, V> next;
public HashNode(K key, V value) {
this.key = key;
this.value = value;
}
}
public class HashMap<K,V>{
private ArrayList<HashNode<K,V>> bucketArray;
private int numBuckets;
private int size;
public HashMap() {
bucketArray = new ArrayList<>();
numBuckets = 10;
size = 0;
for ( int i = 0; i < numBuckets; i ++)
bucketArray.add(null);
}
public int size() { return size;}
public boolean isEmpty() { return size == 0;}
public int getBucketIndex( K key){
int hashCode = key.hashCode();
int index = hashCode % numBuckets;
return index;
}
public V remove(K key){
int bucketIndex = getBucketIndex(key);
HashNode<K,V> head = bucketArray.get(bucketIndex);
HashNode<K,V> prev = null;
while(head != null){
if(head.key.equals(key))
break;
prev = head;
head = head.next;
}
// key not found
if(head == null)
return null;
size--;
if(prev != null)
prev.next = head.next;
else
bucketArray.set(bucketIndex, head.next);
return head.value;
}
public V get(K key){
int bucketIndex = getBucketIndex(key);
HashNode<K,V> head = bucketArray.get(bucketIndex);
while(head!= null){
if(head.key.equals(key))
return head.value;
head = head.next;
}
return null;
}
public void add(K key, V value){
int bucketIndex = getBucketIndex(key);
HashNode<K,V> head = bucketArray.get(bucketIndex);
while(head!= null){
if(head.key.equals(key)){
head.value= value;
return;
}
head = head.next;
}
size++;
head = bucketArray.get(bucketIndex);
HashNode<K,V> newNode = new HashNode<K,V>(key, value);
newNode.next = head;
bucketArray.set(bucketIndex, newNode);
if((1.0*size)/numBuckets >= 0.7){
ArrayList<HashNode<K,V>>temp = bucketArray;
bucketArray = new ArrayList<>();
numBuckets = 2 * numBuckets;
size = 0;
for (int i = 0; i < numBuckets; i ++)
bucketArray.add(null);
for(HashNode<K,V> headNode : temp){
while(headNode != null){
add(headNode.key, headNode.value);
headNode = headNode.next;
}
}
}
}
public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<>();
map.add("this",1);
map.add("coder",2);
map.add("this",4);
map.add("hi",5);
System.out.println(map.size());
System.out.println(map.remove("this"));
System.out.println(map.size());
System.out.println(map.isEmpty());
}
}