-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHashTable.java
More file actions
106 lines (91 loc) · 1.86 KB
/
HashTable.java
File metadata and controls
106 lines (91 loc) · 1.86 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
105
106
public class HashTable<K,V>
{
private final int INITIAL_TABLE_SIZE = 128;
private HashNode[] hashTable;
private int tableSize = INITIAL_TABLE_SIZE;
private int size = 0;
private static int numCollisions = 0;
private static int numResizes = 0;
public HashTable()
{
hashTable = new HashNode[INITIAL_TABLE_SIZE];
}
private int hashFunction(K key)
{
int hash = Math.abs(key.hashCode());
return hash % tableSize;
}
public float loadFactor()
{
return size/(float)tableSize;
}
public void put(K key, V value)
{
int hash = hashFunction(key);
HashNode<K,V> newNode = new HashNode<K,V>(key, value);
//check if load factor is about 0.4
if(loadFactor() > 0.40f)
{
numResizes++;
//double the size of the table
HashNode[] oldHashTable = this.hashTable;
this.hashTable = new HashNode[tableSize*2];
tableSize = tableSize*2;
//remap values to new table
for(int i=0; i<oldHashTable.length; i++)
{
HashNode<K,V> node = oldHashTable[i];
while(node != null)
{
put(node.getKey(), node.getValue());
node = node.getNext();
}
}
}
if(hashTable[hash] != null)
{
System.out.println("COLLISION!!!");
numCollisions++;
//append to linked list
hashTable[hash].setNext(newNode);
}
else
{
hashTable[hash] = newNode;
}
size++;
}
public V get(K key)
{
int hash = hashFunction(key);
HashNode<K,V> hashNode = hashTable[hash];
while(hashNode != null)
{
if(hashNode.getKey().equals(key))
break;
else
hashNode = hashNode.getNext();
}
if(hashNode == null)
return null;
else
return hashNode.getValue();
}
public void delete(K key)
{
int hash = hashFunction(key);
hashTable[hash] = null;
}
public int getSize()
{
return size;
}
public int getNumCollisions()
{
return numCollisions;
}
public int getNumResizes()
{
return numResizes;
}
}