Repository navigation
Expand file tree
/
Copy pathHashTable.java
More file actions
75 lines (70 loc) · 2.5 KB
/
Copy pathHashTable.java
File metadata and controls
75 lines (70 loc) · 2.5 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
import java.util.*;
class HashTable<K, V> {
private ArrayList<HashNode<K, V> > bucketArray;
private int numBuckets;
private int size;
public HashTable() {
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; }
private int hashCode (K key) {
int hash = 7;
hash = 31 * hash + (int) Double.parseDouble(key.toString());
hash = 31 * hash + (int) Double.parseDouble(key.toString());
hash = 31 * hash + (int) Double.parseDouble(key.toString());
return hash;
}
private int getBucketIndex(K key) {
int hashCode = hashCode(key);
int index = hashCode % numBuckets;
// key.hashCode() could be negative.
index = index < 0 ? index * -1 : index;
return index;
}
public void get(K key) {
int bucketIndex = getBucketIndex(key);
int hashCode = hashCode(key);
HashNode<K, V> head = bucketArray.get(bucketIndex);
while (head != null) {
if (head.key.equals(key) && head.hashCode == hashCode)
return;
head = head.next;
}
}
public void add(K key, V value) {
int bucketIndex = getBucketIndex(key);
int hashCode = hashCode(key);
HashNode<K, V> head = bucketArray.get(bucketIndex);
while (head != null) {
if (head.key.equals(key) && head.hashCode == hashCode) {
head.value = value;
return;
}
head = head.next;
}
size++;
head = bucketArray.get(bucketIndex);
HashNode<K, V> newNode = new HashNode<>(key, value, hashCode);
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;
}
}
}
}
}